题解 | #牛奶产量总和#
牛奶产量总和
https://www.nowcoder.com/practice/0932ea3bd8514c79849cc658108053bb?tpId=354&tqId=10591606&ru=/exam/oj&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D354
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 { int sum = 0; /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型 */ public int sumNumbers (TreeNode root) { // write code here fun(root, 0); return sum; } public void fun(TreeNode root, int preNum) { preNum = preNum * 10 + root.val; if (root.left == null && root.right == null) { sum = sum + preNum; return; } if (root.left != null) { fun(root.left, preNum); } if (root.right != null) { fun(root.right, preNum); } } }
知识点:
二叉树 递归
解题思路:
首先,我们需要定义一个树节点的类,用于表示二叉树的节点,每个节点包括产奶量值。