题目链接
- 左叶子之和
代码
递归文章来源:https://www.toymoban.com/news/detail-654562.html
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
if root.left is None and root.right is None:
return 0
leftvalue = self.sumOfLeftLeaves(root.left)
if root.left.left is None and root.left.right is None:
leftvalue = root.left.val
rightvalue = self.sumOfLeftLeaves(root.right)
sum = leftvalue + rightvalue
return sum
迭代文章来源地址https://www.toymoban.com/news/detail-654562.html
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
st = [root]
result = 0
while st:
node = st.pop()
if node.left and node.left.left is None and node.left.right is None:
result += node.left.val
if node.left:
st.append(node.left)
if node.right:
st.append(node.right)
return result
到了这里,关于LeetCode(力扣)404. 左叶子之和Python的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!