算法題--二叉樹各個分支構(gòu)成的十進制數(shù)之和

image.png

0. 鏈接

題目鏈接

1. 題目

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

Note: A leaf is a node with no children.

Example:

Input: [1,2,3]
    1
   / \
  2   3
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.

Example 2:

Input: [4,9,0,5,1]
    4
   / \
  9   0
 / \
5   1
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->0 represents the number 40.
Therefore, sum = 495 + 491 + 40 = 1026.

2. 思路1: BFS

  1. 基本思路是:
  • 利用隊列數(shù)據(jù)結(jié)構(gòu)御毅,存儲每一層的節(jié)點,及每個節(jié)點處的臨時計算結(jié)果
  • 遵循BFS原則, 依次遍歷每一層的節(jié)點, 并計算此時的臨時計算結(jié)果, 當(dāng)遍歷到葉子節(jié)點時, 將此時的臨時結(jié)果累加到返回值中
  1. 分析:
  • 過程中, 每個元素都被訪問1次
  • 存儲空間最多占用的長度為葉子節(jié)點的數(shù)量, 對于一棵完全二叉樹而言, 占用空間最多, 為O(N); 對于一棵單分支二叉樹而言, 占用空間最少, 為O(1)
  1. 復(fù)雜度
  • 時間復(fù)雜度 O(N)
  • 空間復(fù)雜度 最壞及平均O(N), 最好O(1)

3. 代碼

# coding:utf8
import collections


# 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 sumNumbers(self, root: TreeNode) -> int:
        if root is None:
            return 0

        rtn_sum = 0
        node_queue = collections.deque()
        sum_queue = collections.deque()

        node_queue.append(root)
        sum_queue.append(root.val)

        has_began = (root.val > 0)
        while len(node_queue) > 0:
            size = len(node_queue)
            for i in range(size):
                node = node_queue.popleft()
                value = sum_queue.popleft()

                if value > 0:
                    has_began = True
                ratio = 10 if has_began else 0
                if node.left is not None:
                    node_queue.append(node.left)
                    sum_queue.append(value * ratio + node.left.val)
                if node.right is not None:
                    node_queue.append(node.right)
                    sum_queue.append(value * ratio + node.right.val)
                if node.left is None and node.right is None:
                    rtn_sum += value

        return rtn_sum


solution = Solution()

root1 = node = TreeNode(1)
node.left = TreeNode(2)
node.right = TreeNode(3)
print('output1: {}'.format(solution.sumNumbers(root1)))

root2 = node = TreeNode(4)
node.left = TreeNode(9)
node.right = TreeNode(0)
node.left.left = TreeNode(5)
node.left.right = TreeNode(1)
print('output2: {}'.format(solution.sumNumbers(root2)))

root3 = node = TreeNode(1)
node.left = TreeNode(2)
node.left.left = TreeNode(3)
print('output3: {}'.format(solution.sumNumbers(root3)))

root4 = node = TreeNode(2)
print('output4: {}'.format(solution.sumNumbers(root4)))

root5 = node = TreeNode(0)
node.left = TreeNode(3)
node.right = TreeNode(0)
node.left.left = TreeNode(4)
print('output5: {}'.format(solution.sumNumbers(root5)))


輸出結(jié)果

output1: 25
output2: 1026
output3: 123
output4: 2
output5: 34

4. 結(jié)果

image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末县忌,一起剝皮案震驚了整個濱河市筷畦,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌黍判,老刑警劉巖豫尽,帶你破解...
    沈念sama閱讀 222,865評論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異顷帖,居然都是意外死亡美旧,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,296評論 3 399
  • 文/潘曉璐 我一進店門贬墩,熙熙樓的掌柜王于貴愁眉苦臉地迎上來榴嗅,“玉大人,你說我怎么就攤上這事震糖÷伎希” “怎么了?”我有些...
    開封第一講書人閱讀 169,631評論 0 364
  • 文/不壞的土叔 我叫張陵吊说,是天一觀的道長论咏。 經(jīng)常有香客問我,道長颁井,這世上最難降的妖魔是什么厅贪? 我笑而不...
    開封第一講書人閱讀 60,199評論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮雅宾,結(jié)果婚禮上养涮,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好贯吓,可當(dāng)我...
    茶點故事閱讀 69,196評論 6 398
  • 文/花漫 我一把揭開白布懈凹。 她就那樣靜靜地躺著,像睡著了一般悄谐。 火紅的嫁衣襯著肌膚如雪介评。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,793評論 1 314
  • 那天爬舰,我揣著相機與錄音们陆,去河邊找鬼。 笑死情屹,一個胖子當(dāng)著我的面吹牛坪仇,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播垃你,決...
    沈念sama閱讀 41,221評論 3 423
  • 文/蒼蘭香墨 我猛地睜開眼椅文,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了蜡镶?” 一聲冷哼從身側(cè)響起雾袱,我...
    開封第一講書人閱讀 40,174評論 0 277
  • 序言:老撾萬榮一對情侶失蹤恤筛,失蹤者是張志新(化名)和其女友劉穎官还,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體毒坛,經(jīng)...
    沈念sama閱讀 46,699評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡望伦,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,770評論 3 343
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了煎殷。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片屯伞。...
    茶點故事閱讀 40,918評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖豪直,靈堂內(nèi)的尸體忽然破棺而出劣摇,到底是詐尸還是另有隱情,我是刑警寧澤弓乙,帶...
    沈念sama閱讀 36,573評論 5 351
  • 正文 年R本政府宣布末融,位于F島的核電站,受9級特大地震影響暇韧,放射性物質(zhì)發(fā)生泄漏勾习。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,255評論 3 336
  • 文/蒙蒙 一懈玻、第九天 我趴在偏房一處隱蔽的房頂上張望巧婶。 院中可真熱鬧,春花似錦、人聲如沸艺栈。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,749評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽湿右。三九已至巴席,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間诅需,已是汗流浹背漾唉。 一陣腳步聲響...
    開封第一講書人閱讀 33,862評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留堰塌,地道東北人赵刑。 一個月前我還...
    沈念sama閱讀 49,364評論 3 379
  • 正文 我出身青樓,卻偏偏與公主長得像场刑,于是被迫代替她去往敵國和親般此。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,926評論 2 361