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.
方法一:递归调用
时间复杂度:o(n) 空间复杂度:o(1)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if(root==null) return 0;
if(isLeft(root.left)) return root.left.val+sumOfLeftLeaves(root.right); //找到左子叶之后继续找
return sumOfLeftLeaves(root.left)+sumOfLeftLeaves(root.right);
}
private boolean isLeft(TreeNode root){
if(root==null) return false;
return root.left==null&&root.right==null; //子叶是没有左右孩子的结点
}
}
转载于//www.cnblogs.com/shaer/p/10587236.html
还没有评论,来说两句吧...