[LeetCode&Python] Problem 404. Sum of Left Leaves
Posted chiyeung
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode&Python] Problem 404. 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.
# 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的主要内容,如果未能解决你的问题,请参考以下文章
C++&Python描述 LeetCode C++&Python描述 LeetCode 剑指 Offer 22. 链表中倒数第k个节点
[LeetCode&Python] Problem 202. Happy Number
[LeetCode&Python] Problem 520. Detect Capital
[LeetCode&Python] Problem 383. Ransom Note