leetcode 1022. Sum of Root To Leaf Binary Numbers(python)

描述

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:

avater

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

Note:

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

解析

根据题意,只需要将树中从根到叶子结点的所有路径找出来,因为这些路径都是二进制的,所以将这些路径表示的二进制转化成十进制,最后求和即可得到答案,DFS 走起。

解答

class Solution(object):
    def sumRootToLeaf(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        def dfs(root, path):
            if not root.left and not root.right:
                self.res += int(path + str(root.val), 2)
                return
            path += str(root.val)
            if root.left:
                dfs(root.left, path)
            if root.right:
                dfs(root.right, path)
        self.res = 0
        dfs(root, '')
        return self.res

运行结果

Runtime: 24 ms, faster than 79.32% of Python online submissions for Sum of Root To Leaf Binary Numbers.
Memory Usage: 14 MB, less than 54.92% of Python online submissions for Sum of Root To Leaf Binary Numbers.

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

您的支持是我最大的动力

猜你喜欢

转载自blog.csdn.net/wang7075202/article/details/115401163