您的位置:首页 > 其它

leetcode-404. Sum of Left Leaves 求左叶子节点的和,递归

2016-10-14 10:29 477 查看
题目:

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.


题意:

 求左叶子节点的和

代码:

# 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 root == None :

            return 0

        

        tempnode = root.left;

        if tempnode != None and tempnode.left == None and tempnode.right == None :

            return tempnode.val + self.sumOfLeftLeaves(root.right)

        else:

            return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)

笔记:

1、关键是将左叶子节点定义出来

2、python中逻辑运算符 ‘且’ 的表示方法是 and ,  '或' 的表示方法是 or
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: