I prefer to practice my Iteration skill as more as possible. Super easy one Queue concise solution.


  • 0
    public int sumNumbers(TreeNode root) {
            if (root == null) return 0;
            Queue<TreeNode> q = new ArrayDeque<>();
            q.add(root);
            int sum = 0;
            while (!q.isEmpty()) {
                TreeNode node = q.poll();
                if (node.left != null) {
                    node.left.val = node.val * 10 + node.left.val;
                    q.add(node.left);
                }
                if (node.right != null) {
                    node.right.val = node.val * 10 + node.right.val;
                    q.add(node.right);
                }
                if (node.left == null && node.right == null) {
                    sum += node.val;
                }
            }
            return sum;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.