func sumOfLeftLeaves(root *TreeNode) int {
if root == nil {
return 0
}
stack := []*TreeNode{root}
var res int
for len(stack) > 0 {
cur := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if cur.Left != nil && cur.Left.Left == nil && cur.Left.Right == nil {
res += cur.Left.Val
} else if cur.Left != nil {
stack = append(stack, cur.Left)
}
if cur.Right != nil {
stack = append(stack, cur.Right)
}
}
return res
}
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if not root:
return 0
stack = [root]
res = 0
while stack:
cur = stack.pop()
if cur.left and not cur.left.left and not cur.left.right:
res += cur.left.val
elif cur.left:
stack.append(cur.left)
if cur.right:
stack.append(cur.right)
return res
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if not root:
return 0
if root and root.left and not root.left.left and not root.left.right:
return root.left.val + self.sumOfLeftLeaves(root.right)
return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)