Sharing my BFS solution


  • 0
    R
    public class Solution {
    public int sumNumbers(TreeNode root) {
        if(root == null)
            return 0;
        int total = 0;
        Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
        Queue<Integer> sumQueue = new LinkedList<Integer>();
        nodeQueue.add(root);
        sumQueue.add(0);
        while(!nodeQueue.isEmpty()){
            int sum = sumQueue.remove();
            TreeNode node = nodeQueue.remove();
            sum = sum*10 + node.val;
            if(node.left == null && node.right == null){
                total += sum;
            }else{
                if(node.left == null){
                    nodeQueue.add(node.right);
                }else if(node.right == null){
                    nodeQueue.add(node.left);
                }else{
                    nodeQueue.add(node.right);
                    nodeQueue.add(node.left);
                    sumQueue.add(sum);
                }
            sumQueue.add(sum);
            } 
        }
    return total;
    }
    

    }


Log in to reply
 

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