404. Sum of Left Leaves

problem

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.

求所有最下左节点之和
(单个节点,是不算左节点的)

solution

  • 大致方向应该还是两个,递归,压栈

压栈解法

# 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
        """
        stack = [(root, 0)]
        res = 0
        while stack:
            node, sign = stack.pop()
            if node:
                if not node.left and not node.right and sign:
                    res += node.val
                stack.append((node.left, 1))
                stack.append((node.right, 0))
        return res

递归

class Solution(object):
    def __init__(self):
        self.res = 0
    def sumOfLeftLeaves(self, root, sign=0):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root:
            if not root.left and not root.right and sign:
                self.res += root.val
            self.sumOfLeftLeaves(root.left, 1)
            self.sumOfLeftLeaves(root.right,0)
        return self.res
            
posted @ 2016-10-15 15:31  Salmd  阅读(134)  评论(0)    收藏  举报