java solution using queue


  • 0
    J

    using a FIFO queue to store treeNodes;find the left leaves and calculate the sum

    public int sumOfLeftLeaves(TreeNode root) {
            if(root==null){
                return 0;
            }
            Queue<TreeNode> queue=new LinkedList<TreeNode>();
            queue.add(root);
            int result=0;;
            while(queue.peek()!=null){
                TreeNode node=queue.poll();
                if(node.left!=null){
                    queue.add(node.left);
                    if(node.left.left==null && node.left.right==null){//find the left leaves
                        result+=node.left.val;
                    }
                }
                if(node.right!=null){
                    queue.add(node.right);
                }
            }
            return result;
        }
    

Log in to reply
 

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