zoukankan      html  css  js  c++  java
  • 404. Sum of Left Leaves

    https://leetcode.com/problems/sum-of-left-leaves/#/description

    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.


    Hint:

    Q: How to define if a node is a left leaf?

    A: When the node exists and it has no right or left child.

    See node 9 and 15 in the given example.

    i.e. if root.left and not root.left.left and not root.left.right (== True)

    It means the root.left is the left leaf of root. 

    Sol1: 

    Recursion. (I prefer recursion more than iteration.)

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def sumOfLeftLeaves(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            # recursion
            
            # base case: node is none
            if root is None:
                return 0
            # recursive case: left child is/isn't child 
            if root.left and not root.left.left and not root.left.right:
                return root.left.val + self.sumOfLeftLeaves(root.right)
            return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)

    Note:

    1 When we find a left leaf, we should return the sum of its value and the right half of the root.  That's where recursion comes into play. 

    2 The final return result should be the sum of all values of the left subtrees and all right subtrees. Do it recursively.

    3 Don't need to use while loop to advance nodes in recursion.  

    Sol2:

    Recursion.

    In this solution, we use varible to store sum of left leaf values. Easier to understand.

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def sumOfLeftLeaves(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            # recursion
            
            # base case: node is none
            sum = 0
            if root is None:
                return 0
            # recursive case: left child is/isn't child 
            if root.left and not root.left.left and not root.left.right:
                sum += root.left.val 
            sum += self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)
            return sum

    Note:

    1 "sum += root.left.val " stores values of left leaves in left subtress. No need to return anything.

    "sum += self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)" returns all branches of the tree. It will be returned. 

    Sol3:

    Iteration using stack. (It is more efficient to use recursion!)

    It's basically the mutation of traversing the tree using iteration(stack). Not recommended.  Refer here to see more ways to implement tree traversal.

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def sumOfLeftLeaves(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            # iteration
            #  traverse the whole tree using stack. If the left child is leave, add it to the result.
            
            if not root:
                return 0
            s = [root]
            res = 0
            while s:
                tmp = s.pop()
                if tmp.left:
                    s.append(tmp.left)
                    if not tmp.left.left and not tmp.left.right:
                        res += tmp.left.val
                if tmp.right:
                    s.append(tmp.right)
            return res

     

     

     

    
    
  • 相关阅读:
    9.1、PHP 中的函数
    7.2.2、二维数组中包含自定义键数组的打印
    Windows 8 VHD 概述与使用
    8.2、磁盘、目录和文件计算
    7.2.6、随机取出数组中的某个下标
    7.2.3、数组排序
    7.2.7、数组指针的操作
    CentOS6 下 JDK7 + jBoss AS 7 环境搭建
    How to iterate HashMap using JSTL forEach loop
    windows 8 非内置系统管理员获得完整权限的方法
  • 原文地址:https://www.cnblogs.com/prmlab/p/6964248.html
Copyright © 2011-2022 走看看