【问题标题】:leetcode question 437 why also apply DFS to children nodes?leetcode 437 为什么还要对子节点应用 DFS?
【发布时间】:2020-04-21 15:23:33
【问题描述】:

我正在研究 Leetcode 问题 437 Path Sum III,并在 java 上使用 DFS 解决它:

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

    public static int pathSum(TreeNode root, int sum) {
        return dfs(root, sum)+pathSum(root.left, sum)+pathSum(root.right, sum);
    }

    public static int dfs(TreeNode root, int sum) {
        if (root == null) return 0;
        int count = 0;
        if (root.val == sum) count++;

        count += dfs(root.left, sum - root.val);
        count += dfs(root.right, sum - root.val);

        return count;
    }

在pathSum()方法的return语句中,为什么我们需要“dfs(root, sum)+dfs(root.left, sum)+dfs(root.right, sum)”,而不仅仅是“dfs(root,总和)(这个返回错误的答案)”? 有人解释说这是因为“路径不需要从根或叶开始或结束”(来自 lc437)。如果是这样,那为什么我们只需要也只检查根的孩子,而不是根的孩子的孩子呢?

【问题讨论】:

  • 发布的代码有效吗?当 r root 为空时,pathSum 应该抛出 NullPointerException。

标签: java depth-first-search


【解决方案1】:

要避免NullPointerException,您需要对pathSum 进行一些小改动:

public static int pathSum(TreeNode root, int sum) {
    if( root == null) return 0;
    return dfs(root, sum)+pathSum(root.left, sum)+pathSum(root.right, sum);
}

考虑给定的树:

现在让我们从根节点开始遍历树,寻找长度为 8 的路径。 这可以通过从pathSum 中省略+pathSum(root.left, sum)+pathSum(root.right, sum); 来实现:

public static int pathSum(TreeNode root, int sum) {
    if( root == null) return 0;
    //check root only 
    return dfs(root, sum);//+pathSum(root.left, sum)+pathSum(root.right, sum);
}

返回0是因为没有路径,从根开始,长度为0。
所以现在我们要检查子树。是否有任何从 root.right 开始的长度为 8 的路径?我们可以这样做:

public static int pathSum(TreeNode root, int sum) {
    if( root == null) return 0;
    //check root, check root.right and return the sum 
    return dfs(root, sum) + pathSum(root.right, sum) ;//+pathSum(root.left, sum);
}

这应该返回 1,因为有一个路径从root.right 开始,长度为 8:-3 -> 11
我希望这能阐明为什么我们需要检查 root 以及 left 和 right 以获得完整的结果。


旁注:您可以通过以非递归方式检查所有树节点来获得相同的结果。例如:
    Stack<TreeNode> stack = new Stack<>();
    stack.add(root);
    int count = 0;
    while (! stack.isEmpty()){
        TreeNode node = stack.pop();
        count += dfs(node,8);
        if(node != null) {
            stack.add(node.left);
            stack.add(node.right);
        }
    }
    System.out.println(count); 

【讨论】:

    【解决方案2】:

    因为通过在树上左右移动,我们将遍历它。我们必须遍历树才能找到路径总和。如果你只去根,那么你就不会在树中移动,从而导致错误的答案。

    public static int pathSum(TreeNode root, int sum) {
            return dfs(root, sum)+pathSum(root.left, sum)+pathSum(root.right, sum);
        }
    

    它的作用是将每个节点视为计算路径的子树的根,通过计算较小树的路径之和,您将获得较大树的路径之和。

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2015-07-23
      • 1970-01-01
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-24
      相关资源
      最近更新 更多