【Leetcode_总结】1022. 从根到叶的二进制数之和 - python

Q:

给出一棵二叉树,其上每个结点的值都是 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

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

思路:递归

代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def sumRootToLeaf(self, root: TreeNode) -> int:
        res = 0
        if root  == None:
            return res
        else:
            return self.dfs(root,0)
    
        
    def dfs(self,root,acc):
        ret = 0
        tmp = int(bin(acc)[2:] + str(root.val),2)
        if root.left == None and root.right == None:
            return tmp
        if root.left:
            ret = self.dfs(root.left,tmp)
        if root.right:
            ret += self.dfs(root.right,tmp)
        return ret
        

猜你喜欢

转载自blog.csdn.net/maka_uir/article/details/89450567