[LeetCode] 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.
这道题让我们求一棵二叉树的所有左子叶的和,那么看到这道题我们知道这肯定是考二叉树的遍历问题,那么最简洁的写法肯定是用递归,由于我们只需要累加左子叶之和,那么我们在进入递归函数的时候需要知道当前结点是否是左子节点,如果是左子节点,而且该左子节点再没有子节点了说明其是左子叶,那么我们将其值加入结果res中,我们用一个bool型的变量,如果为true说明当前结点是左子节点,若为false则说明是右子节点,不做特殊处理,整个来说就是个递归的先序遍历的写法,参见代码如下:
在原函数中检查当前节点的左子节点是否是左子叶,如果是的话,则返回左子叶的值加上对当前结点的右子节点调用递归的结果;如果不是的话,我们对左右子节点分别调用递归函数,返回二者之和
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if(root == null)
return 0;
if(isLeaf(root.left))
return root.left.val + sumOfLeftLeaves(root.right);
return sumOfLeftLeaves(root.right) + sumOfLeftLeaves(root.left);
}
private boolean isLeaf(TreeNode root){
if(root == null)
return false;
return root.left == null && root.right == null;
}
}