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

    https://leetcode.com/problems/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.

    Solution

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    # recursion
    class Solution(object):
        def sumOfLeftLeaves(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            if not root:
                return 0
            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)
    
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    # Iterative
    class Solution(object):
        def sumOfLeftLeaves(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            if not root:
                return 0
            s = [root]
            res = 0
            while s:
                node = s.pop()
                if node.left:
                    s.append(node.left)
                    if not node.left.left and not node.left.right:
                        res += node.left.val
                if node.right:
                    s.append(node.right)
            return res
    
  • 相关阅读:
    版本控制,django缓存,跨域问题解决
    Linux之文件系统结构
    Linux之定时任务
    Linux之LVM
    Linux之硬盘与分区
    Linux之文件重定向与查找
    Linux之文件压缩
    Linux之文件权限
    Linux之用户管理
    Linux之文件管理
  • 原文地址:https://www.cnblogs.com/binwone/p/6044893.html
Copyright © 2011-2022 走看看