题目描述

题解
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val
* TreeNode left
* TreeNode right
* TreeNode() {}
* TreeNode(int val) { this.val = val
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val
* this.left = left
* this.right = right
* }
* }
*/
// DFS / 前序遍历
// 基本上跟【Leetcode】112. 路径总和 和 【Leetcode】113. 路径总和 II
// 很像,在前序遍历模板基础上改一下计算规则就行了。
// path记录路径的数字叠加,res记录不同路径之间的求和。
// 前序遍历前,将当前数字堆叠到path中(高位左移,root.val作为低位插入。
// 当遇到叶子结点,直接将path累加到res中。
// 当递归preOrder结束之后,将原来堆叠到path的root.val去掉(低位去掉)
//
// 执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
// 内存消耗:35.2 MB, 在所有 Java 提交中击败了99.98%的用户
class Solution {
int res = 0
int path = 0
public int sumNumbers(TreeNode root) {
preOrder(root)
return res
}
public void preOrder(TreeNode root) {
if (root == null) {
return
}
path = path * 10 + root.val
if (root.left == null && root.right == null) {
res += path
}
preOrder(root.left)
preOrder(root.right)
path = path / 10
}
}