题解 | #牛奶产量总和#

牛奶产量总和

https://www.nowcoder.com/practice/0932ea3bd8514c79849cc658108053bb

知识点

树,深度遍历

解题思路

要知道每个路径相加的总和,深度遍历整棵树,将父节点相加的值preNum传入到当前节点,当前节点的值总和就是preNum*10+节点的值,当左右节点为空时,就把preNum的值加入到最终答案ans的总和中。

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整型
     */
     int sum = 0;
    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);
        }
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务