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.
给出一个二叉树,计算所有左叶子的和
思路:
可以用中序遍历,因为是左叶子,所以要判断是左节点同时节点的左右子树都是null
遍历时用boolean来表示是否是左节点
class Solution {
int sum = 0;
public int sumOfLeftLeaves(TreeNode root) {
midOrderTraversal(root, false);
return sum;
}
public void midOrderTraversal(TreeNode root, boolean left) {
if (root == null) {
return;
}
if (left && root.left == null && root.right == null) {
sum += root.val;
}
midOrderTraversal(root.left, true);
midOrderTraversal(root.right, false);
}
}