Problem
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.
ExampleInput: [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.
class Solution { public int sumNumbers(TreeNode root) { if (root == null) return 0; return sum(root, 0); } private int sum(TreeNode root, int cur) { if (root == null) return 0; if (root.left == null && root.right == null) return cur*10+root.val; return sum(root.left, cur*10+root.val)+sum(root.right, cur*10+root.val); } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/71120.html
摘要:解題思路本題要求所有從根結(jié)點(diǎn)到葉子節(jié)點(diǎn)的路徑和,我們用遞歸實(shí)現(xiàn)。結(jié)束條件當(dāng)遇到葉子節(jié)點(diǎn)時(shí),直接結(jié)束,返回計(jì)算好的如果遇到空節(jié)點(diǎn),則返回?cái)?shù)值。 Sum Root to Leaf NumbersGiven a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a numbe...
摘要:遞歸法復(fù)雜度時(shí)間空間遞歸??臻g思路簡(jiǎn)單的二叉樹(shù)遍歷,遍歷時(shí)將自身的數(shù)值加入子節(jié)點(diǎn)。一旦遍歷到葉子節(jié)點(diǎn)便將該葉子結(jié)點(diǎn)的值加入結(jié)果中。 Sum Root to Leaf Numbers Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.An...
摘要: 112. Path Sum Problem Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. Note: A leaf is a node...
摘要:解題思路利用遞歸,對(duì)于每個(gè)根節(jié)點(diǎn),只要左子樹(shù)和右子樹(shù)中有一個(gè)滿足,就返回每次訪問(wèn)一個(gè)節(jié)點(diǎn),就將該節(jié)點(diǎn)的作為新的進(jìn)行下一層的判斷。代碼解題思路本題的不同點(diǎn)是可以不從開(kāi)始,不到結(jié)束。代碼當(dāng)前節(jié)點(diǎn)開(kāi)始當(dāng)前節(jié)點(diǎn)左節(jié)點(diǎn)開(kāi)始當(dāng)前節(jié)點(diǎn)右節(jié)點(diǎn)開(kāi)始 Path SumGiven a binary tree and a sum, determine if the tree has a root-to-lea...
摘要:小鹿題目路徑總和給定一個(gè)二叉樹(shù)和一個(gè)目標(biāo)和,判斷該樹(shù)中是否存在根節(jié)點(diǎn)到葉子節(jié)點(diǎn)的路徑,這條路徑上所有節(jié)點(diǎn)值相加等于目標(biāo)和。說(shuō)明葉子節(jié)點(diǎn)是指沒(méi)有子節(jié)點(diǎn)的節(jié)點(diǎn)。 Time:2019/4/26Title: Path SumDifficulty: EasyAuthor: 小鹿 題目:Path Sum(路徑總和) Given a binary tree and a sum, determin...
閱讀 2120·2021-11-24 09:39
閱讀 1503·2019-08-30 15:44
閱讀 1954·2019-08-29 17:06
閱讀 3406·2019-08-29 16:32
閱讀 3552·2019-08-29 16:26
閱讀 2662·2019-08-29 15:35
閱讀 3033·2019-08-29 12:50
閱讀 1646·2019-08-29 11:15