leetcode 404. Sum of Left Leaves

来源:互联网 发布:淘宝面膜排行榜 编辑:程序博客网 时间:2024/06/05 21:13

Python leetcode

404. Sum of Left Leaves


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.


主要是求一个树的左叶节点的和。

#coding=utf-8
# 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
        """

        if not root:
            return 0
        if 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)

    # 求右节点的和
    def sumOfRightLeaves(self,root):
        if  not root:return 0
        if root.right and not root.right.left and not root.right.right:
            return root.right.val + self.sumOfLeftLeaves(root.left)
        return self.sumOfRightLeaves(root.left)+self.sumOfRightLeaves(root.right)

tree=TreeNode(10)
tree.left=TreeNode(9);tree.right=TreeNode(20)
tree.right.left=TreeNode(15);tree.right.right=TreeNode(7)

s=Solution()
print s.sumOfLeftLeaves(tree)
print s.sumOfRightLeaves(tree)
0 0
原创粉丝点击