摘要:解題思路本題要求所有從根結(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 Numbers
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.
For example, 1 / 2 3 The root-to-leaf path 1->2 represents the number 12. The root-to-leaf path 1->3 represents the number 13. Return the sum = 12 + 13 = 25.
解題思路
本題要求所有從根結(jié)點(diǎn)到葉子節(jié)點(diǎn)的路徑和,我們用遞歸實(shí)現(xiàn)。
結(jié)束條件:當(dāng)遇到葉子節(jié)點(diǎn)時(shí),直接結(jié)束,返回計(jì)算好的sum;如果遇到空節(jié)點(diǎn),則返回?cái)?shù)值0。
2.代碼
public class Solution { public int sumNumbers(TreeNode root) { return sum(root,0); } private int sum(TreeNode root, int cur){ if(root==null) return 0; cur=10*cur+root.val; if(root.left==null&&root.right==null) return cur; else return sum(root.left,cur)+sum(root.right,cur); } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/69812.html
摘要:解題思路利用遞歸,對(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...
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 tota...
摘要:遞歸法復(fù)雜度時(shí)間空間遞歸棧空間思路簡(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...
摘要:解題思路用遞歸實(shí)現(xiàn)很簡(jiǎn)單,對(duì)于每個(gè)根節(jié)點(diǎn),最大深度就等于左子樹(shù)的最大深度和右子樹(shù)的最大深度的較大值。解題思路本題的注意點(diǎn)在于如果某個(gè)根節(jié)點(diǎn)有一邊的子樹(shù)為空,那么它的深度就等于另一邊不為空的子樹(shù)的深度,其他的邏輯與上一題相同。 Maximum Depth of Binary TreeGiven a binary tree, find its maximum depth. The maxi...
摘要:但是本題的難點(diǎn)在于,使用遞歸實(shí)現(xiàn),但是前面的第四種情況不能作為遞歸函數(shù)的返回值,所以我們需要定義兩個(gè)值,代表單邊路徑的最大值,用于遞歸用于和回路的較大值。 Binary Tree Maximum Path SumGiven a binary tree, find the maximum path sum. For this problem, a path is defined as a...
閱讀 944·2021-11-23 09:51
閱讀 1004·2021-11-18 10:02
閱讀 1942·2021-09-10 11:27
閱讀 3153·2021-09-10 10:51
閱讀 791·2019-08-29 15:13
閱讀 2077·2019-08-29 11:32
閱讀 2509·2019-08-29 11:25
閱讀 3055·2019-08-26 11:46