404. Sum of Left Leaves 404.左叶总和

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.

复习时还不会的地方:
就是直接表示就行了,root.left不为空,并且root.left.left,root.left.right都为空
还要注意在内部定义sum = 0;

 

不是计算么,怎么变成recursive。好吧,还是在外面,还是算DC,就是直接拿来计算了。计算题直接拿来计算就行了
“最左边”这个特质就是左边无、右边也无了。好吧,不说我还真看不出来。

都要加到sum上去才行

首先是左节点,但是不知道怎么表示
好吧,可以先判断root.left != null,然后使用root.left.left == null

sum += root.left.val;这里已经加过了,加一遍就行了,sum()再加就重复了

 

sumOfLeftLeaves(root.right);//divide的一侧不论如何都要进行,不需要加else

 

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        //cc
        if (root == null) {
            return 0;
        }
        
        int sum = 0;
        if (root.left != null) {
            if ((root.left.left == null) && (root.left.right == null))
                sum += root.left.val;
            else sumOfLeftLeaves(root.left);
        }
        
        sumOfLeftLeaves(root.right);
        
        return sum;
    }
}
View Code

 

 
posted @ 2020-05-24 10:48  苗妙苗  阅读(108)  评论(0)    收藏  举报