LeetCode-Python-1022. 从根到叶的二进制数之和

642 篇文章 23 订阅

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

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

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

 

示例:

输入:[1,0,1,0,1,0,1]
输出:22
解释:(100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22

 

提示:

  1. 树中的结点数介于 1 和 1000 之间。
  2. node.val 为 0 或 1 。

思路:

基础题,DFS+回溯找到每一条从根节点到叶节点的Path,存在res里,

然后线性扫描res这个数组,把每一条path利用int(BIN,2)函数转成十进制,再加到rres中。

# 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):
        """
        :type root: TreeNode
        :rtype: int
        """
        res = []
        
        def dfs(root, tmp):
            if not root:
                return
            
            tmp += str(root.val)
            if not root.left and not root.right:
                res.append(tmp[:])
                
            dfs(root.left, tmp)
            dfs(root.right, tmp)
            tmp = tmp[:-1]
   
        dfs(root, "")
        rres = 0
        for item in res:
            rres += int(item, 2) 
            rres %= (10 ** 9 + 7)
        
        return rres

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值