这是我参与2022首次更文挑战的第37天,活动详情查看:2022首次更文挑战」
求根节点到叶节点数字之和 Sum root to leaf numbers
LeetCode传送门 129. 求根节点到叶节点数字之和
题目
给你一个二叉树的根节点 root ,树中每个节点都存放有一个 0 到 9 之间的数字。 每条从根节点到叶节点的路径都代表一个数字:
例如,从根节点到叶节点的路径 1 -> 2 -> 3 表示数字 123 。 计算从根节点到叶节点生成的 所有数字之和 。
叶节点 是指没有子节点的节点。
You are given the root of a binary tree containing digits from 0 to 9 only.
Each root-to-leaf path in the tree represents a number.
For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123. Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.
A leaf node is a node with no children.
Example:
Input: root = [1,2,3]
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.
Input: root = [4,9,0,5,1]
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->0 represents the number 40.
Therefore, sum = 495 + 491 + 40 = 1026.
Constraints:
- The number of nodes in the tree is in the range [1, 1000].
- 0 <= Node.val <= 9
- The depth of the tree will not exceed 10.
思考线
解题思路
这个题是一个典型的可以用递归来解决的问题。
刚开始我思考的时候想着,能不能从 leaf
节点向上相加。但是思考后没有从这个点得到想要的结果。
那我们试着从上往下如何得到正确的数字呢?
比如对于一个节点路线4 -> 9 -> 5
,我们从4
, 40 + 9
, 490 + 5
,来得到最终的值,然后向上返回相加的结果。
我想到使用DFS
来解决这个问题。我们首先要写一个dfs
算法函数。
在整个过程中我们有一个问题,如何保存之前的值,我们可以通过传递一个参数pre
来保存这个之前的计算结果。
接下来在编写DFS
函数我们需要考虑两点
- 如果没有子节点,则证明到了叶子结点,把
pre * 10
+ 当前节点的值 返回即可。 - 如果有子节点,我们递归子节点即可。
代码实现如下:
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function sumNumbers(root: TreeNode | null): number {
return dfs(root, 0);
};
function dfs(root: TreeNode, pre: number) {
if(!root) return 0;
pre = pre * 10 + root.val
if(!root.left &&!root.right) return pre;
return dfs(root.left, pre) + dfs(root.right, pre)
}
时间复杂度
O(n): n为二叉树的节点数
这就是我对本题的解法,如果有疑问或者更好的解答方式,欢迎留言互动。