摘要:递归法复杂度时间空间递归栈空间思路简单的二叉树遍历,遍历时将自身的数值加入子节点。一旦遍历到叶子节点便将该叶子结点的值加入结果中。
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) 递归栈空间
思路简单的二叉树遍历,遍历时将自身的数值加入子节点。比如节点A的值是1,其左子节点的值是2,则将左子节点变为12。一旦遍历到叶子节点便将该叶子结点的值加入结果中。
代码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); } } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/66158.html
摘要:解题思路本题要求所有从根结点到叶子节点的路径和,我们用递归实现。结束条件当遇到叶子节点时,直接结束,返回计算好的如果遇到空节点,则返回数值。 Sum Root to Leaf NumbersGiven a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a numbe...
摘要:只要我们能够有一个以某一中间路径和为的哈希表,就可以随时判断某一节点能否和之前路径相加成为目标值。 最新更新请见: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...
摘要:小鹿题目路径总和给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。说明叶子节点是指没有子节点的节点。 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...
摘要:解题思路利用递归,对于每个根节点,只要左子树和右子树中有一个满足,就返回每次访问一个节点,就将该节点的作为新的进行下一层的判断。代码解题思路本题的不同点是可以不从开始,不到结束。代码当前节点开始当前节点左节点开始当前节点右节点开始 Path SumGiven a binary tree and a sum, determine if the tree has a root-to-lea...
阅读 1469·2023-04-26 00:20
阅读 886·2023-04-25 21:49
阅读 789·2021-09-22 15:52
阅读 562·2021-09-07 10:16
阅读 946·2021-08-18 10:22
阅读 2635·2019-08-30 14:07
阅读 2218·2019-08-30 14:00
阅读 2625·2019-08-30 13:00