一文彻底搞懂「二叉树路径和」问题

今天这篇文章我们来总结一下 LeetCode 上关于「二叉树路径和」的问题。

我们今天所讲的二叉树上的结点,都是下面这个 TreeNode 类的对象

public class TreeNode {
	int val;
 	TreeNode left;
 	TreeNode right;
    TreeNode(int x) { 
        val = x; 
    }
}

我们这里所说的路径,指的是从某一结点到其某一后代结点经过的路线,路径上不包含重复结点。而「路径和」指的是路径上所有结点的val的和。

第 112 题:二叉树中是否存在某个路径和

题目链接:112. Path Sum

原题如下:

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Note: A leaf is a node with no children.

题意大概是:

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

说明: 叶子节点是指没有子节点的节点。

例如,给定如下二叉树,以及目标和 sum=22,应该返回 true,因为该二叉树中存在存在一条从根节点到叶子结点的路径 5->4->11->2,其路径和是 22。

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

这道题中对于路径的定义更加严格了,路径的起点必须是二叉树的根节点,终点必须是叶子节点。

思路一:递归

这道题用递归来解的话非常简单,我们把二叉树的根节点记为 root,如果我们想判断一颗二叉树是否存在路径和 sum,那么只需判断其左子树或者右子树是否存在路径和 sum-root.val。

代码如下:

public boolean hasPathSum(TreeNode root, int sum) {
    if (root == null)
        return false;
    int val = root.val;
    if (root.left == null && root.right == null && val == sum)
        return true;
    return hasPathSum(root.left, sum - val) || hasPathSum(root.right, sum - val);
}

复杂度分析

  • 时间复杂度:O(n),n 是二叉树上结点的个数。最坏情况下,需要遍历二叉树上的所有结点才能确定是否存在路径和为 sum 的路径。
  • 空间复杂度:O(h),h 是二叉树的高度。该算法递归的深度取决于二叉树的深度。

思路二:迭代——用栈代替递归

利用栈先入后出的特点,我们可以对思路一中的递归代码进行改造,代码如下:

public boolean hasPathSum_iteration(TreeNode root, int sum){
    if (root == null)
        return false;
    Stack<TreeNode> stack = new Stack<>();
    Stack<Integer> path = new Stack<>();

    TreeNode t = root;
    Integer val = root.val;
    stack.push(t);
    path.push(val);
    while (!stack.isEmpty()){
        t = stack.pop();
        val = path.pop();
        if (t.left == null && t.right == null && sum == val){ //到达了叶子结点,且路径总和正好等于sum
            return true;
        }
        if (t.left != null){
            stack.push(t.left);
            path.push(val + t.left.val);
        }
        if (t.right != null){
            stack.push(t.right);
            path.push(val + t.right.val);
        }
    }
    return false;
}

复杂度分析

  • 时间复杂度:O(n)。
  • 空间复杂度:O(h)。栈的大小同样取决于二叉树的高度,但是对于栈的操作显然要比递归更加节省计算机资源。

第113 题:列出所有满足给定路径和的路径

题目链接:113. Path Sum II

原题如下:

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

Note: A leaf is a node with no children.

题意大概是:

给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

说明: 叶子节点是指没有子节点的节点。

例如,给定如下二叉树,以及路径和 sum=22,

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

应该返回:

[
   [5,4,11,2],
   [5,8,4,5]
]

这一题的路径起点也必须是根结点,终点必须是叶子结点。跟上一题相比,这道题的复杂之处在于,我们不仅要判断是否存在符合条件的路径,还要返回该路径,而且返回的路径中结点必须遵循从起点到终点的顺序(什么?你问我是怎么知道的?第一次提交的时候就是因为顺序不对,没有通过)。

思路一:递归

这道题同样可以用递归来解。如果二叉树存在路径和为 sum 的路径,那么根节点 root 的左子树或者右子树必然存在路径和为 sum-root.val 的路径。

总体思路就是这个样子,但是具体到代码层面,还有一些细节需要注意。由于返回的路径必须是根结点到叶子结点的顺序,所以递归的过程中我们需要维护一个列表,里面记录着抵达当前结点之前经过的路径,比如上面那个例子中,当我们递归到7这个结点的时候,列表里面的元素应该是[5,4,11],当我们递归到13这个结点的时候,列表里面的元素应该是[5,8]

代码如下:

public List<List<Integer>> pathSum(TreeNode root, int sum) {
    List<List<Integer>> res = new ArrayList<>();
    if (root != null){
        pathSum(res, new ArrayList<>(), root, sum);
    }
    return res;
}

public void pathSum(List<List<Integer>> res, List<Integer> curPath, TreeNode root, int sum){
    if (root.left == null && root.right == null){ //递归到叶子结点时
        if (root.val == sum){
            curPath.add(root.val);
            res.add(curPath);
            return;
        }else {
            return;
        }
    }

    curPath.add(root.val);
    if (root.left != null){
        List<Integer> left_children_path = new ArrayList<>(curPath);  //每开启一个新的递归,都要复制一份新的curPath
        pathSum(res, left_children_path, root.left, sum - root.val);
    }
    if (root.right != null){
        List<Integer> right_children_path = new ArrayList<>(curPath);  //每开启一个新的递归,都要复制一份新的curPath
        pathSum(res, right_children_path, root.right, sum - root.val);
    }
}

如果每次递归都创建一个新的列表的话,会很浪费时间,所以我们对上面的代码加以改造,递归过程中,只需维护一个数组就可以。代码如下:

public List<List<Integer>> pathSum(TreeNode root, int sum) {
    List<List<Integer>> res = new ArrayList<>();
    int[] path = new int[maxDepth(root)]; //计算二叉树的高度
    if (root != null){
        pathSum(res, path, root, sum, 0);
    }
    return res;
}

//idx记录的是当前递归的深度,即当前访问的是二叉树的第几层
public void pathSum(List<List<Integer>> res, int[] curPath, TreeNode root, int sum, int idx){
    if (root.left == null && root.right == null){
        if (root.val == sum){
            curPath[idx] = root.val;
            List<Integer> al = new ArrayList<>(idx+1);
            for(int i = 0; i <= idx; i++){
                al.add(curPath[i]);
            }
            res.add(al);
            return;
        }else {
            return;
        }
    }

    curPath[idx] = root.val;
    if (root.left != null){
        pathSum(res, curPath, root.left, sum - root.val, idx + 1);
    }
    if (root.right != null){
        pathSum(res, curPath, root.right, sum - root.val, idx + 1);
    }
}

private int maxDepth(TreeNode root) {
    if (root == null)
        return 0;
    if (root.right == null && root.left == null)
        return 1;
    if (root.right == null)
        return maxDepth(root.left) + 1;
    if (root.left == null)
        return maxDepth(root.right) + 1;
    return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}

复杂度分析

  • 时间复杂度:改造前的代码时间复杂度是 O ( h 2 ) O(h^2) O(h2),因为每次递归都要复制列表,列表的长度等于根节点到当前结点的高度,改造后的时间复杂度是 O(n)。
  • 空间复杂度:改造前的代码空间复杂度是 O ( h 2 ) O(h^2) O(h2),因为递归的最大深度是 h,而每次递归都要保存从根结点到当前结点的路径。改造后的空间复杂度是 O(h)。

通过分析时空复杂度可以看到,虽然同样是递归,但是优化前与优化后差别还是很大的。

思路二:迭代——用栈代替递归

同样,这个算法也可以用栈来实现,代码如下:

public List<List<Integer>> pathSum(TreeNode root, int sum) {
    List<List<Integer>> res = new ArrayList<>();
    if (root == null){
        return res;
    }
    int[] path = new int[maxDepth(root)];
    Stack<TreeNode> nodeStack = new Stack<>();
    Stack<Integer> level = new Stack<>(); //记录当前访问到第几层了
    Stack<Integer> path_sum = new Stack<>(); //记录根结点到当前结点的路径和
    int val = root.val;
    nodeStack.push(root);
    level.push(0);
    path_sum.push(val);
    while (!nodeStack.isEmpty()){
        TreeNode t = nodeStack.pop();
        int curLevel = level.pop();
        val = path_sum.pop();
        path[curLevel] = t.val;
        if (t.left == null && t.right == null && sum == val) { //到达了叶子结点,且路径总和正好等于sum
            List<Integer> al = new ArrayList<>(curLevel + 1);
            for(int i = 0; i <= curLevel; i++){
                al.add(path[i]);
            }
            res.add(al);
        }
        if (t.left != null){
            nodeStack.push(t.left);
            path_sum.push(val + t.left.val);
            level.push(curLevel + 1);
        }
        if (t.right != null){
            nodeStack.push(t.right);
            path_sum.push(val + t.right.val);
            level.push(curLevel + 1);
        }
    }
    return res;
}
private int maxDepth(TreeNode root) {
    if (root == null)
        return 0;
    if (root.right == null && root.left == null)
        return 1;
    if (root.right == null)
        return maxDepth(root.left) + 1;
    if (root.left == null)
        return maxDepth(root.right) + 1;
    return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}

复杂度分析

  • 时间复杂度:O(n)。
  • 空间复杂度:O(h)。

第 437 题:计算满足给定路径和的路径个数

题目链接:437. Path Sum III

原题如下:

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

题意大概是:

给定一个二叉树,它的每个结点都存放着一个整数值。找出路径和等于给定数值的路径总数。

路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。

二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。

例如给定下面这个二叉树及路径和 sum:root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

     10
     /  \
    5   -3
   / \      \
  3   2    11
 / \    \
3  -2   1

应该返回 3,因为和等于 8 的路径有:

5 -> 3
5 -> 2 -> 1
-3 -> 11

这道题对于路径的定义与我们文章开头的定义一样。

直觉

假设 F(node, sum) 为以节点 node 开头的路径和为 s 的路径个数, n o d e i node_i nodei 是第 i 个结点,那么 ∑ i = 0 n F ( n o d e i , s u m ) \sum^n_{i=0}F(node_i,sum) i=0nF(nodei,sum) 就是我们要求的最终结果。因此我们需要遍历每个节点,计算出 F(node, sum)。而 F(node, sum)=F(node.left, sum-node.val)+F(node.right, sum-node.val)。

关于遍历二叉树,不熟悉的可以参考这篇文章:二叉树的遍历详解,而计算 F(node, sum) 则可以采用递归的方式,代码如下:

public int pathSum(TreeNode root, int sum) {
    if (root == null)
        return 0;
    int res = 0;
    Stack<TreeNode> stack = new Stack<>();
    TreeNode t = root;
    while (true){
        while (t != null){
            res += helper(t, sum);
            if (t.right != null){
                stack.push(t.right);
            }
            t = t.left;
        }
        if (stack.empty()) break;
        t = stack.pop();
    }
    return res;
}

public int helper(TreeNode root, int sum) {
    int res = 0;
    if (root.val == sum){
        res += 1;
    }
    if (root.left != null){
        res += helper(root.left, sum - root.val);
    }
    if (root.right != null){
        res += helper(root.right, sum - root.val);
    }
    return res;
}

复杂度分析

  • 时间复杂度: O ( n 2 ) O(n^2) O(n2)。遍历二叉树的时间复杂度是 O(n),而每访问一个结点,都需要历以这个结点为根节点的二叉树,以计算 F(node, sum),时间复杂度又是 O(n),所以两者一叠加,总的时间复杂度就是 O ( n 2 ) O(n^2) O(n2)
  • 空间复杂度: O ( h ) O(h) O(h)

优化——利用前缀和

前缀和就是从根结点到当前结点的路径上所有结点的值的总和。如果结点 x 与结点 y 是祖先结点与后代结点的关系,并且 pre_sum_x-pre_sum_y=sum,那么结点 x 与结点 y 之间的路径的路径和一定等于 sum。

对二叉树进行先序遍历,同时维护一个哈希表,哈希表的 key 是前缀和,value 是该前缀和出现的次数,哈希表记录的是当前结点的每个祖先结点的前缀和的个数。

比如示例中的那个二叉树,当我们访问到1那个结点的时候,它有 3 个祖先结点,分别是10, 5, 2,每个祖先结点的前缀和分别是10, 15, 17,那么哈希表中存储的键值对应该是:

key	  value
10	   1
15     1 
17     1

当前结点的前缀和是 18,示例中 sum=8,那我们就在哈希表中找有几个祖先结点的前缀和是 18-sum=18-8=10,通过哈希表我们发现有 1 个祖先结点的前缀和是 10,所以只有一个以当前结点结尾的路径的路径和是8,那么最终结果+1,然后继续遍历,直到整棵二叉树被遍历完。

代码如下:

public int pathSum(TreeNode root, int sum) {
    Map<Integer, Integer> map = new HashMap<>();
    map.put(0, 1);
    return pathSumFrom(root, 0, sum, map);
}
private int pathSumFrom(TreeNode root, int sum, int target, Map<Integer, Integer> map){
    if (root == null)
        return 0;
    sum += root.val;
    int res = map.getOrDefault(sum - target, 0);
    map.put(sum, map.getOrDefault(sum, 0) + 1);
    res += pathSumFrom(root.left, sum, target, map)
        + pathSumFrom(root.right, sum, target, map);
    map.put(sum, map.get(sum) - 1);
    return res;
}

上述代码是用递归实现的,当然也可以用迭代的方式实现。代码如下:

public int pathSum_prefixSumIteration(TreeNode root, int sum) { //前缀和迭代版
    if (root == null)
        return 0;
    int res = 0;
    Stack<TreeNode> nodes = new Stack<>();
    Stack<Integer> prefixSumStack = new Stack<>();
    Map<TreeNode, Boolean> map = new HashMap<>();
    Map<Integer, Integer> prefixSumMap = new HashMap<>();

    nodes.push(root);
    prefixSumStack.push(root.val);
    prefixSumMap.put(0, 1);

    int val = 0;
    while (!nodes.isEmpty()){
        TreeNode t = nodes.peek();
        val = prefixSumStack.peek();
        if (map.get(t) == null){
            res += prefixSumMap.getOrDefault(val - sum, 0);
            prefixSumMap.put(val, prefixSumMap.getOrDefault(val, 0) + 1);
            map.put(t, true);
        }
        if (t.left != null && map.get(t.left) == null){
            nodes.push(t.left);
            prefixSumStack.push(val + t.left.val);
        }else if (t.right != null && map.get(t.right) == null) {
            nodes.push(t.right);
            prefixSumStack.push(val + t.right.val);
        }else {
            nodes.pop();
            int ps = prefixSumStack.pop();
            Integer ps_count = prefixSumMap.get(ps);
            if (ps_count != null && ps_count != 0) {
                prefixSumMap.put(ps, ps_count - 1);
            }
        }
    }
    return res;
}

复杂度分析

  • 时间复杂度:O(n)。
  • 空间复杂度:O(h)。

总结

通过这几道题,我们可以发现,解决二叉树的路径和问题,通常可以分解成左子树和右子树的子问题,把两个子问题的解组合起来就是最终的解。不仅是二叉树的路径和问题,解决二叉树的其他相关问题通常也是采用分治的思想。只要能写出递推公式,就可以很容易地写出相应的递归代码,剩下的就是优化的问题了。

  • 7
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值