gold-4-12


给定一棵二叉树,其中每个节点都含有一个整数数值(该值或正或负)。设计一个算法,打印节点数值总和等于某个给定值的所有路径的数量。注意,路径不一定非得从二叉树的根节点或叶节点开始或结束,但是其方向必须向下(只能从父节点指向子节点方向)。

示例:
给定如下二叉树,以及目标和 sum = 22

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1

返回:

3
解释:和为 22 的路径有:[5,4,11,2], [5,8,4,5], [4,11,7]

提示:

  • 节点总数 <= 10000

//leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int result = 0;


    public int pathSum(TreeNode root, int sum) {
        Map<Integer, Integer> depthMap = new HashMap<>();
        
        getDepth(root, depthMap, 0, sum);
        
        return result;
    }

    private void getDepth(TreeNode node, Map<Integer, Integer> depthMap, int lastDepth, int sum) {
        if (node == null) {
            return;
        }

        int curDepth = lastDepth + node.val;
        int curNum = depthMap.getOrDefault(curDepth, 0) + 1;

        int sub = curDepth - sum;
        result += (depthMap.getOrDefault(sub, 0));
        depthMap.put(curDepth, curNum);

        if (curDepth == sum) {
            result++;
        }

        getDepth(node.left, depthMap, curDepth, sum);
        getDepth(node.right, depthMap, curDepth, sum);
        depthMap.put(curDepth, curNum - 1);
    }

}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !