题解 | #牛群特殊路径的数量#

牛群特殊路径的数量

https://www.nowcoder.com/practice/1c0f95d8396a432db07945d8fe51a4f5

考察递归算法在二叉树的应用,利用深度优先算法遍历每个节点,每次遍历的时候用目标值减去上一个节点的值就可以了,当遍历到节点时如果值为0就证明存在这个路径。计数加一。

完整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类
     * @param sum int整型
     * @return int整型
     */
    
    public int pathSum (TreeNode root, int sum) {
        // write code here
        if (root == null) return 0;
        int res = search(root,sum);
        res += pathSum(root.left,sum);
        res += pathSum(root.right, sum);
        return res;
    }

    public int search(TreeNode root, int sum) {
        int total = 0;
        if (root == null) return 0;
        if (sum == root.val) {
            total ++;
        }
        total+=search(root.left, sum-root.val);
        total+=search(root.right, sum-root.val);
        return total;
    }

}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务