您的位置:首页 > 其它

Sum of Left Leaves

2016-12-08 21:01 211 查看
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.


求树的所有左叶子的和

public class SumofLeftLeaves {
public int sumOfLeftLeaves(TreeNode root) {
int sum = 0;
if (root == null)
return 0;
if (isLeave(root.left))
sum += root.left.val;
sum += sumOfLeftLeaves(root.left);
sum += sumOfLeftLeaves(root.right);

return sum;
}

public  boolean isLeave(TreeNode node) {
if (node == null)
return false;
if (node.left == null && node.right == null)
return true;
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: