前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Q404 Sum of Left Leaves

Q404 Sum of Left Leaves

作者头像
echobingo
发布2018-04-25 17:17:27
6040
发布2018-04-25 17:17:27
举报

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

Example:
代码语言:javascript
复制
    3
   / \
  9  20
    /  \
   15   7

There are two left leaves in the binary tree, 
with values 9 and 15 respectively. Return 24.
解题思路:
  • 首先明确左叶子的定义,即当前结点的左子树非空,且左子树是一个叶子,用代码表示为 root.left != None and root.left.left == None and root.left.right == None
  • 当在左子树上找到左叶子后(比如例子中的 9),还需要在右子树上找到左叶子之和(递归),并且相加。用代码表示为 root.left.val + self.sumOfLeftLeaves(root.right)
  • 如果当前结点的左子树不是叶子,则递归求左右子树的左子树之和。用代码表示为 self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)
Python 实现:
代码语言:javascript
复制
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0
        if root.left != None and root.left.left == None and root.left.right == None:
            return root.left.val + self.sumOfLeftLeaves(root.right) # 左叶子加上在右子树中求左叶子之和
        return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right) # 求左右子树中左叶子之和
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.03.08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Example:
  • 解题思路:
  • Python 实现:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档