摘要:遞歸法復(fù)雜度時(shí)間空間遞歸棧空間思路簡單的二叉樹遍歷,遍歷時(shí)將自身的數(shù)值加入子節(jié)點(diǎn)。一旦遍歷到葉子節(jié)點(diǎn)便將該葉子結(jié)點(diǎn)的值加入結(jié)果中。
Sum Root to Leaf Numbers
遞歸法 復(fù)雜度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.
時(shí)間 O(N) 空間 O(N) 遞歸??臻g
思路簡單的二叉樹遍歷,遍歷時(shí)將自身的數(shù)值加入子節(jié)點(diǎn)。比如節(jié)點(diǎn)A的值是1,其左子節(jié)點(diǎn)的值是2,則將左子節(jié)點(diǎn)變?yōu)?2。一旦遍歷到葉子節(jié)點(diǎn)便將該葉子結(jié)點(diǎn)的值加入結(jié)果中。
代碼public class Solution { int sum = 0; public int sumNumbers(TreeNode root) { if(root != null) getSum(root); return sum; } private void getSum(TreeNode n){ if(n.left == null && n.right == null){ sum += n.val; } if(n.left != null){ n.left.val += n.val * 10; getSum(n.left); } if(n.right != null){ n.right.val += n.val * 10; getSum(n.right); } } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/66158.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...
摘要:只要我們能夠有一個(gè)以某一中間路徑和為的哈希表,就可以隨時(shí)判斷某一節(jié)點(diǎn)能否和之前路徑相加成為目標(biāo)值。 最新更新請(qǐng)見:https://yanjia.me/zh/2019/01/... Path Sum I Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that addin...
摘要:小鹿題目路徑總和給定一個(gè)二叉樹和一個(gè)目標(biāo)和,判斷該樹中是否存在根節(jié)點(diǎn)到葉子節(jié)點(diǎn)的路徑,這條路徑上所有節(jié)點(diǎn)值相加等于目標(biāo)和。說明葉子節(jié)點(diǎn)是指沒有子節(jié)點(diǎn)的節(jié)點(diǎn)。 Time:2019/4/26Title: Path SumDifficulty: EasyAuthor: 小鹿 題目:Path Sum(路徑總和) Given a binary tree and a sum, determin...
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...
摘要:解題思路利用遞歸,對(duì)于每個(gè)根節(jié)點(diǎn),只要左子樹和右子樹中有一個(gè)滿足,就返回每次訪問一個(gè)節(jié)點(diǎn),就將該節(jié)點(diǎn)的作為新的進(jìn)行下一層的判斷。代碼解題思路本題的不同點(diǎn)是可以不從開始,不到結(jié)束。代碼當(dāng)前節(jié)點(diǎn)開始當(dāng)前節(jié)點(diǎn)左節(jié)點(diǎn)開始當(dāng)前節(jié)點(diǎn)右節(jié)點(diǎn)開始 Path SumGiven a binary tree and a sum, determine if the tree has a root-to-lea...
閱讀 1540·2023-04-26 00:20
閱讀 1130·2023-04-25 21:49
閱讀 809·2021-09-22 15:52
閱讀 583·2021-09-07 10:16
閱讀 977·2021-08-18 10:22
閱讀 2672·2019-08-30 14:07
閱讀 2244·2019-08-30 14:00
閱讀 2659·2019-08-30 13:00