美文网首页
404. Sum of Left Leaves

404. Sum of Left Leaves

作者: AlanGuo | 来源:发表于2016-10-04 14:26 被阅读0次

    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.

    这道题其实并不复杂,一定要戒骄戒躁仔细审题,题目问的是 left leaves,而不是 left node。

    发现自己心很急,碰到题目怕自己做的慢,所以急忙看题,急忙开始做。这样会出大事的。

    一定要沉下心来。

    Solution:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution 
    {
        public int sum = 0;
        
        public int sumOfLeftLeaves(TreeNode root) 
        {
            sumHelper(root);
            return sum;
        }
        public void sumHelper(TreeNode node)
        {
            if(node == null)
                return;
            else if(node.left != null && node.left.left == null && node.left.right == null)
            {
                sum += node.left.val;
            }
            sumHelper(node.left);
            sumHelper(node.right);
        }
    }
    

    思路就是简单地做一个 Traversal(顺序并不重要,这里用了pre-order),然后判断当前遍历到的节点是否有 leftChild,如果有,当前节点的 leftChild 是否是一个 leaf(判断它的 left 和 right 是否为空),如果是则将这个 leftChild 的 val 累加。

    *post-order:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution 
    {
        public int sum = 0;
        
        public int sumOfLeftLeaves(TreeNode root) 
        {
            sumHelper(root);
            return sum;
        }
        
        public void sumHelper(TreeNode node)
        {
            if(node == null)
                return;
            
            sumHelper(node.left);
            sumHelper(node.right);
            
            if(node.left != null && node.left.left == null && node.left.right == null)
            {
                sum += node.left.val;
            }
        }
        
        
    }
    

    相关文章

      网友评论

          本文标题:404. Sum of Left Leaves

          本文链接:https://www.haomeiwen.com/subject/cgajyttx.html