码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode&Python] Problem 404. Sum of Left Leaves

时间:2018-12-02 13:35:35      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:node   root   value   with   ble   etc   app   roo   highlight   

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.

# 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 method
        ‘‘‘
        def rer(node,left):
            if not node:
                return 0
            if left:
                if node.left or node.right:
                    return rer(node.left,True)+rer(node.right,False)
                else:
                    return node.val
            else:
                return rer(node.right,False)+rer(node.left,True)
        
        return rer(root,False)
        ‘‘‘
        # Non-recursion method
        ans=0
        if root:
            stack=[root]
            
            while stack:
                node=stack.pop()
                if node.left:
                    if not node.left.left and not node.left.right:
                        ans+=node.left.val
                    else:
                        stack.append(node.left)
                if node.right:
                    stack.append(node.right)
        return ans

  

[LeetCode&Python] Problem 404. Sum of Left Leaves

标签:node   root   value   with   ble   etc   app   roo   highlight   

原文地址:https://www.cnblogs.com/chiyeung/p/10053015.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!