Simple Breadth First Search Modification - Java


  • 0
    O

    A very simple modification of the breadth first search gives the solution.

    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            if (root == null) return 0;
            if (root.left == null && root.right == null) return 0;
            Queue<TreeNode> q = new ArrayDeque<TreeNode>();
            int leftSum = 0;
            q.add(root);
            TreeNode node;
            while (!q.isEmpty()) {
                node = q.remove();
                if (node.left != null) {
                    if (node.left.left == null && node.left.right == null) {
                        leftSum += node.left.val;
                    }
                    q.add(node.left);
                }
                if (node.right != null) {
                    q.add(node.right);
                }
            }
            return leftSum;
        }
    }
    

Log in to reply
 

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