题解 | #牛奶产量总和# java
牛奶产量总和
https://www.nowcoder.com/practice/0932ea3bd8514c79849cc658108053bb
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
List<Integer> res = new ArrayList<>();
public int sumNumbers(TreeNode root) {
// write code here
if (root == null)
return 0;
dfs(root, root.val);
int sum = 0;
for (int i = 0; i < res.size(); i++) {
sum += res.get(i);
}
return sum;
}
private void dfs(TreeNode root, int target) {
if (root == null)
return;
if (root.left == null && root.right == null) {
res.add(target);
}
if (root.left != null)
dfs(root.left, target * 10 + root.left.val);
if (root.right != null)
dfs(root.right, target * 10 + root.right.val);
}
}
该代码使用的编程语言是Java
这道题考察的知识点是二叉树的遍历和递归。
代码的文字解释如下:
sumNumbers方法接收一个TreeNode类型的参数root,返回一个整数值。- 首先创建一个空的整型向量
res,用于存储计算得到的数字。 - 如果
root为空,则直接返回 0。 - 调用
dfs方法进行深度优先搜索(DFS),初始时传入root和root的值。 - 创建一个变量
sum,初始值为 0,用于累加计算得到的数字之和。 - 遍历
res向量,将其中的数字累加到sum中。 - 返回
sum的值作为结果。

