404. 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.
My Solutions:
左叶节点的定义是本身是叶(不是root,且左右孩子为null),且是左节点。因此,只有满足这两个条件的节点值才会返回。
方法1:dfs recursive
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
return dfs(root, false);
}
public int dfs(TreeNode root, boolean isLeft){
if (root.left == null && root.right == null && isLeft) return root.val;
else {
int lsum = 0, rsum = 0;
if (root.left != null) lsum = dfs(root.left, true);
if (root.right != null) rsum = dfs(root.right, false);
return lsum + rsum;
}
}
}
方法2:dfs iterative。dfs一律用stack做,因为最后进的最先出,所以只要node.left != null,就一直压栈
public class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
int ans = 0;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.empty()) {
TreeNode node = stack.pop();
if (node.left != null) {
//这个节点就是左叶节点
if (node.left.left == null && node.left.right == null)
ans += node.left.val;
else
stack.push(node.left);
}
// 只有有右节点不为null且有孩子时,才压这个节点。如果本身是个右叶节点,不需要压
if (node.right != null) {
if (node.right.left != null || node.right.right != null)
stack.push(node.right);
}
}
return ans;
}
}
方法3:bfs iterative。bfs一律用queue做,因为先进先出,所以总是loop完一层,再进入下一层
public class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
int res = 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
TreeNode curr = queue.poll();
// curr.left is a left leaf
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;
}
}
Last updated