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
.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int sumNumbers(TreeNode root) { return solve(root, 0); } private int solve(TreeNode root, int level) { if (root == null) { return 0; } if (root.left==null && root.right==null) { return level + root.val; } int nextLevel = (level + root.val) * 10; int left = solve(root.left, nextLevel); int right = solve(root.right, nextLevel); return left + right; } }
相关推荐
129. 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 ...
python python_leetcode题解之129_Sum_Root_to_Leaf_Numbers
javascript js_leetcode题解之129-sum-root-to-leaf-numbers.js
在本压缩包中,我们关注的是一个与Python编程和LeetCode面试相关的题目,具体是第129题——"Sum Root to Leaf Numbers"(根到叶节点数字之和)。这是一道典型的树形结构问题,涉及到二叉树的遍历。在LeetCode上,...
numbers 2020-01-22 226 翻转二叉树 2020-01-23 95 不同的二叉搜索树 -变种 96 before 2020-01-24 110 平衡二叉树 -结束之后完成 1227 飞机座位分配概率 2020-01-27 208 字典树 2020-01-28 116 Populating Next ...
- **Sum Root to Leaf Numbers**:计算二叉树所有从根到叶子节点的路径之和。 4. **动态规划(Dynamic Programming)**: - **Best Time To Buy and Sell Stock**:股票交易的最佳时机问题。 - **Unique Paths**...
二叉搜索树迭代器-Sum Root to Leaf Numbers 广度优先搜索 -二叉树级顺序遍历-二叉树级顺序遍历II - 二叉树之字形层序遍历-课程安排-课程表二-岛屿数量-太平洋大西洋水流-周边地区-对称树- 克隆图- 字梯-字梯II 回溯...
leetcode 530 LeetCode 问题列表,包括锁定的问题。 [1028] ...Numbers Easy (45.80 %) [1021] Remove Outermost Parentheses Easy (80.59 %) [1020] Number of Enclaves Medium (54.07 %) [1019] Next G
lru cache leetcode leetcode 记录自己刷leetcode时遇到的一些值得记下来的题目, 分为一些子项 bytedance daily:每日一题 struct-algorithm:数据结构/算法先关 ...sum-root-to-leaf-numbers best-time-to-buy
gas station leetcode 在牛客网上的在线编程中的leetcode在线编程题解 代码中有详细题解 ...sum-root-to-leaf-numbers 动态规划 distinct-subsequences 递归 valid-palindrome 模拟 pascals-triangle 模拟 pasca
Sum_Root_to_Leaf_Numbers DFS Surrounded_Regions 由四周‘O’开始向内检索,利用第三个字符对可以变换的‘O’进行暂存 Word_Lader BFS,避免DFS记录以遍历的节点错误,且保证优先找到最短的路径, 按照图的方法判断...