Python实现"左叶子之和"的两种方法

题目

给定一颗二叉树,返回它所有左叶子节点之和

举例

    3
   / \
  9  20
    /  \
   15   7
return 24

递归方法

def sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        if not root.left and not root.right:   #当前节点不存在左右子树
            return 0
        if not root.left and root.right:       #当前节点只有右子树
            return self.sumOfLeftLeaves(root.right)
        if root.left and not root.right:     #当前节点只有左子树
            if not root.left.left and not root.left.right:   #当前节点的左节点不存在左右子树
                return root.left.val
            else:
                return self.sumOfLeftLeaves(root.left)
        sum = 0
        if root.left and root.right:        #当前节点既有左子树又有右子树
            if not root.left.left and not root.left.right:         #当前节点的左子树没有左右节点
                sum += root.left.val
            else:
                sum += self.sumOfLeftLeaves(root.left)
            sum += self.sumOfLeftLeaves(root.right)
        return sum

简化递归写法(参考他人)

def sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        sum = 0
        if root.left and not root.left.left and not root.left.right:
            sum += root.left.val
        sum += self.sumOfLeftLeaves(root.left)
        sum += self.sumOfLeftLeaves(root.right)
        return sum
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容