LeetCode1022.Sum of Root To Leaf Binary Numbers(从根到叶的二进制数之和)

本文详细解析了LeetCode上的1022题——从根到叶的二进制数之和,介绍了题目的背景、难度、示例及解决方案。通过定义递归函数getSum,实现了对二叉树中所有叶子节点从根到叶路径表示的二进制数求和,最终返回以10^9+7为模的结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1022.Sum of Root To Leaf Binary Numbers(从根到叶的二进制数之和)

Description

Given a binary tree, each node has value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.

For all leaves in the tree, consider the numbers represented by the path from the root to that leaf.

Return the sum of these numbers.


给出一棵二叉树,其上每个结点的值都是 01 。每一条从根到叶的路径都代表一个从最高有效位开始的二进制数。例如,如果路径为 0 -> 1 -> 1 -> 0 -> 1,那么它表示二进制数 01101,也就是 13

对树上的每一片叶子,我们都要找出从根到该叶子的路径所表示的数字。

10^9 + 7 为模,返回这些数字之和。

题目链接:https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/

个人主页:http://redtongue.cn or https://redtongue.github.io/

Difficulty: easy

Example 1:

在这里插入图片描述

Input: [1,0,1,0,1,0,1]
Output: 22
Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22

Note:

  • The number of nodes in the tree is between 1 and 1000.
  • node.val is 0 or 1.
  • The answer will not exceed 2^31 - 1.

分析

  • 定义getSum(root,s=0)函数用于得到以root为根节点的二叉树表示的二进制之和;
  • s表示遍历到当前节点,之前的父节点表示的数,若root=None,返回0,此路不通;
  • 反之,node记录左右子树的结果和,s(s=s*2+root.val)更新,若node=0,返回s,反之返回node;
  • 返回getSum(root),s默认零。

参考代码

#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 sumRootToLeaf(self, root):
    def getSum(root,s=0):
        if(root == None):
            return 0
        else:
            s=s*2+root.val
            node=0
            if(root.left):
                node+=getSum(root.left,s)
            if(root.right):
                node+=getSum(root.right,s)
            return s if node==0 else node
    return getSum(root)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值