zoukankan      html  css  js  c++  java
  • 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.

    不是计算么,怎么变成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
    
    

     

     
  • 相关阅读:
    python的logging库
    python的os库
    python的setup和teardown
    CF339D Xenia and Bit Operations线段树
    poj3311Hie with the Pie状压dp
    poj3254Corn Fields状压Dp
    CF414BMashmokh and ACMDP
    母函数6连杀
    母函数hdu1085
    UVA 1401Remember the WordDp
  • 原文地址:https://www.cnblogs.com/immiao0319/p/12949015.html
Copyright © 2011-2022 走看看