左叶子之和
程序员文章站
2022-07-14 18:25:12
...
计算给定二叉树的所有左叶子之和。
示例:
3
/ \
9 20
/ \
15 7在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
来源:力扣(LeetCode)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def readTree(self, left, right, n):
if left==None and right==None:
return
if None!=left and None==left.left and None==left.right:
n.append(left.val)
if left!=None:
self.readTree(left.left, left.right, n)
if right!=None:
self.readTree(right.left, right.right,n)
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if root==None:
return 0
elif root.left==None and root.right==None:
return 0
else:
n=[]
self.readTree(root.left, root.right, n)
return sum(n)
上一篇: 左叶子之和
下一篇: 深入理解Android事件分发机制