摘要:遞歸法復雜度時間空間遞歸??臻g思路簡單的二叉樹遍歷,遍歷時將自身的數(shù)值加入子節(jié)點。一旦遍歷到葉子節(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 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.
時間 O(N) 空間 O(N) 遞歸??臻g
思路簡單的二叉樹遍歷,遍歷時將自身的數(shù)值加入子節(jié)點。比如節(jié)點A的值是1,其左子節(jié)點的值是2,則將左子節(jié)點變?yōu)?2。一旦遍歷到葉子節(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); } } }
文章版權歸作者所有,未經(jīng)允許請勿轉載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉載請注明本文地址:http://m.hztianpu.com/yun/66158.html
摘要:解題思路本題要求所有從根結點到葉子節(jié)點的路徑和,我們用遞歸實現(xiàn)。結束條件當遇到葉子節(jié)點時,直接結束,返回計算好的如果遇到空節(jié)點,則返回數(shù)值。 Sum Root to Leaf NumbersGiven a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a numbe...
摘要:只要我們能夠有一個以某一中間路徑和為的哈希表,就可以隨時判斷某一節(jié)點能否和之前路徑相加成為目標值。 最新更新請見: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...
摘要:小鹿題目路徑總和給定一個二叉樹和一個目標和,判斷該樹中是否存在根節(jié)點到葉子節(jié)點的路徑,這條路徑上所有節(jié)點值相加等于目標和。說明葉子節(jié)點是指沒有子節(jié)點的節(jié)點。 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...
摘要:解題思路利用遞歸,對于每個根節(jié)點,只要左子樹和右子樹中有一個滿足,就返回每次訪問一個節(jié)點,就將該節(jié)點的作為新的進行下一層的判斷。代碼解題思路本題的不同點是可以不從開始,不到結束。代碼當前節(jié)點開始當前節(jié)點左節(jié)點開始當前節(jié)點右節(jié)點開始 Path SumGiven a binary tree and a sum, determine if the tree has a root-to-lea...
閱讀 1604·2023-04-26 00:20
閱讀 1217·2023-04-25 21:49
閱讀 871·2021-09-22 15:52
閱讀 649·2021-09-07 10:16
閱讀 1031·2021-08-18 10:22
閱讀 2726·2019-08-30 14:07
閱讀 2296·2019-08-30 14:00
閱讀 2725·2019-08-30 13:00