404. Sum of Left Leaves - Easy
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.
M1: recursive
time: O(n), space: O(height)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int sumOfLeftLeaves(TreeNode root) { if(root == null) { return 0; } int sum = 0; if(root.left != null && root.left.left == null && root.left.right == null) { sum += root.left.val; } sum += sumOfLeftLeaves(root.left); sum += sumOfLeftLeaves(root.right); return sum; } }
M2: iterative
对于每一个节点,检查它的left child是不是leaf,如果是就加到sum中,如果不是就把left child加入stack。
对于每一个节点的right child,如果它不是leaf就加入stack中
time: O(n), space: O(N) -- 最多一层节点的个数
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int sumOfLeftLeaves(TreeNode root) { Stack<TreeNode> stack = new Stack<>(); if(root == null) { return 0; } int sum = 0; stack.push(root); while(!stack.isEmpty()) { TreeNode tmp = stack.pop(); if(tmp.left != null) { if(tmp.left.left == null && tmp.left.right == null) { sum += tmp.left.val; } else { stack.push(tmp.left); } } if(tmp.right != null) { if(tmp.right.left != null || tmp.right.right != null) { stack.push(tmp.right); } } } return sum; } }