[leetcode] 1022. Sum of Root To Leaf Binary Numbers

Description

You are given the root of a binary tree where each node has a 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. The answer is guaranteed to fit in a 32-bits integer.

Example 1:

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

Example 2:

Input: root = [0]
Output: 0

Example 3:

Input: root = [1]
Output: 1

Example 4:

Input: root = [1,1]
Output: 3

Constraints:

  • The number of nodes in the tree is in the range [1, 1000].
  • Node.val is 0 or 1.

分析

题目的意思是:求出从跟结点到叶子结点构成的二进制数的和。这道题递归的方法需要用val记录当前二进制的值,当遍历到叶子结点的时候需要加入到结果集合res中,最后遍历res求和就行了。我看了一下参考答案,是用的移位操作和栈实现迭代方法。

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def solve(self,root,val):
        if(root is None):
            return 
        val=val+str(root.val)
        if(root.left is None and root.right is None):
            self.res.append(val)
            return 
        self.solve(root.left,val)
        self.solve(root.right,val)
        
    def sumRootToLeaf(self, root: TreeNode) -> int:
        val=''
        self.res=[]
        self.solve(root,val)
        ans=0
        for item in self.res:
            ans+=int(item,2)
        return ans

猜你喜欢

转载自blog.csdn.net/w5688414/article/details/109268274