LeetCode404. 左叶子之和
- 题目链接
- 代码
题目链接
- 左叶子之和
代码
递归
# 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
迭代
# 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