找出给定二叉树中,所有左叶子的值之和。
样例
3
/ \
9 20
/ \
15 7
这棵二叉树中,有两个左叶子结点,它们的值分别为9和15。因此返回24。
解题思路:
递归。如何判断一个节点是左叶子节点(解决这个问题的核心):对于一个节点root,root.left不为空,且 root.left.left、root.left.right为空,则root.left这个节点是左叶子节点。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: t
* @return: the sum of all left leaves
*/
public int sumOfLeftLeaves(TreeNode root) {
// Write your code here
sum = 0;
helper(root);
return sum;
}
private int sum;
private void helper(TreeNode root){
if(root == null)
return;
if(root.left != null && root.left.left == null && root.left.right == null){
sum += root.left.val;
}
helper(root.left);
helper(root.right);
}
}