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

来源:互联网 发布:人工智能的威胁 编辑:程序博客网 时间:2024/06/06 00:22

题目:

Find the sum of all left leaves in a given binary tree.

Example:

    3   / \  9  20    /  \   15   7There 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





0 0