题解 | #牛奶产量总和#
牛奶产量总和
https://www.nowcoder.com/practice/0932ea3bd8514c79849cc658108053bb
考察二叉树的中序遍历算法。
使用中序遍历记录下每个从根节点到叶子节点的值,最后加起来求和就可以了。
完整Java代码如下
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整型
*/
public static Integer target = 0;
public int sumNumbers (TreeNode root) {
search(root, 0);
return target;
}
public void search(TreeNode root, int sum) {
if (root == null) {
return;
}
sum = sum * 10 + root.val;
if (root.left == null && root.right == null) {
target += sum;
}
search(root.left, sum);
search(root.right, sum);
}
}


