Sum of Left Leaves

Find the sum of all left leaves in a given binary tree.

Example:

    3
   / \
  9  20
    /  \
   15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

Tips:

简单的递归,也附上iterative的方法。主要是要加isLeft的条件。

Code:

Recursive:

public class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        return helper(root, false);
    }

    public int helper(TreeNode root, boolean isLeft) {
        if (root == null) return 0;
        if (root.left == null && root.right == null && isLeft) return root.val;
        int left = helper(root.left, true);
        int right = helper(root.right, false);
        return left + right;
    }
}

Iterative:

public int sumOfLeftLeaves(TreeNode root) {
    int res = 0;

    Stack<TreeNode> stack = new Stack<>();
    stack.push(root);

    while (!stack.isEmpty()) {
        TreeNode node = stack.pop();
        if (node != null) {
            if (node.left != null && node.left.left == null && node.left.right == null)
                res += node.left.val;
            stack.push(node.left);
            stack.push(node.right);
        }
    }

    return res;
}

BFS:

public class Solution {
  public int sumOfLeftLeaves(TreeNode root) {
      if(root == null || root.left == null && root.right == null) return 0;

      int res = 0;
      Queue<TreeNode> queue = new LinkedList<>();
      queue.offer(root);

      while(!queue.isEmpty()) {
          TreeNode curr = queue.poll();

          if(curr.left != null && curr.left.left == null && curr.left.right == null) res += curr.left.val;
          if(curr.left != null) queue.offer(curr.left);
          if(curr.right != null) queue.offer(curr.right);
      }
      return res;
  }

}

results matching ""

    No results matching ""