【LeetCode】1022. Sum of Root To Leaf Binary Numbers 解題報告(Python)

做者: 負雪明燭
id: fuxuemingzhu
我的博客: http://fuxuemingzhu.cn/node


題目地址:https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/python

題目描述

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.ide

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 modulo 10^9 + 7.this

Example 1:spa

此處輸入圖片的描述

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

Note:code

  1. The number of nodes in the tree is between 1 and 1000.
  2. node.val is 0 or 1.

題目大意

二叉樹的每一個節點的數值有0和1,從根節點到葉子節點的一條路徑就會構成了一個二進制字符串,求全部路徑構成的二進制字符串轉成整數的和。blog

解題方法

DFS

最簡單的方法就是把全部的路徑遍歷一遍,而後計算每條路徑構成的二進制字符串表示的整數的最大值便可。遞歸

我認爲遞歸最重要的是明白遞歸函數的定義,若是不能明白定義,那麼就寫不出正確的代碼。圖片

這個題定義了一個函數,查找的是在遍歷這個節點之時,已經路過的路徑(包括當前節點)。在其中判斷若是該節點是葉子節點,那麼更新全部的路徑和。

Python的整數不會越界,這題中每經歷過一個節點,就把以前的路徑*2 + 當前的節點值當作路徑表示的整數。

Python代碼以下:

# 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 """
        if not root: return 0
        self.res = 0
        self.dfs(root, root.val)
        return self.res

    def dfs(self, root, preSum):
        if not root.left and not root.right:
            self.res = (self.res + preSum) % (10 ** 9 + 7)
            return
        if root.left:
            self.dfs(root.left, preSum * 2 + root.left.val)
        if root.right:
            self.dfs(root.right, preSum * 2 + root.right.val)

日期

2019 年 4 月 7 日 —— 周賽bug了3次。。

相關文章
相關標籤/搜索