【问题标题】:Recurse within binary tree's node class在二叉树的节点类中递归
【发布时间】:2015-09-02 02:31:23
【问题描述】:

我已经成功编写了一个方法来打印以给定节点为根的子树中所有节点的值(代码粘贴在下面的标签“工作代码”下)。但是,此 printTree 方法位于 Main 类中(而不是位于 Node 类本身中)。我想知道是否有可能(并且理想?)重写代码以使 printTree 方法位于 Node 类本身中?我的尝试如下(代码粘贴在“非工作代码”标签下),但它引发了空指针异常。谢谢!

工作代码:

public class Node {

    int value;
    Node left;
    Node right;

    public Node(int value, Node left, Node right)
    {
        this.value = value;
        this.left = left;
        this.right = right;
    }
}

public class Main {


    public static void printTree(Node current)
    {

        if (current != null)
        {
            System.out.println(current.value);
            printTree(current.left);
            printTree(current.right);
        }

        return;
    }


    public static void main(String[] args) {
    // write your code here

        Node a = new Node(3, new Node(4, null, null), new Node(5, null, null));

        printTree(a);

    }
}

非工作代码(在节点类中):

public void printTree()
{
    Node current = this;

    if (current != null)
    {
        System.out.println(current.value);
        current.left.printTree();
        current.right.printTree();
    }

    return;
}

【问题讨论】:

  • 我认为问题可能与 Node current = this 这一行有关,但我不知道如何解决。

标签: java recursion tree binary-tree depth-first-search


【解决方案1】:

问题不在Node current = this; 行。但是在

current.left.printTree();
current.right.printTree();

行。

因为即使 current 不为 null,current.left 或 current.right 也可能为 null。你正试图在一个空对象上调用printTree()

修复:

if (current != null)
{
    System.out.println(current.value);
    if (current.left != null)
        current.left.printTree();
    if (current.right != null)
        current.right.printTree();
}

【讨论】:

  • 谢谢!我理解你想要做什么,但我担心的是,现在我们要检查一个节点是否为空两次(例如,第一次是当你做 if (current.left != null) 时,第二次是当你做 if (current ! =空))。有没有办法重写代码,这样我们就不会对同一个节点进行多次空检查?
  • 其实,current != null 检查已经没有必要了。就像 Abishek 自己在其他地方指出的那样,current 永远不能为空,因为它是从 this 分配的,而this 永远不能为空。
  • 您可以删除if (current != null) 检查。因为你的电流总是thisthis 永远不会为空。
  • 或者更好的是,您根本不需要current 参考。可以直接拨打left.printTree()right.printTree()
  • 谢谢。澄清一下:在这个递归中,我们有两个递归案例,但没有基本案例,对吧?第一个递归案例是 if (current.left != null),第二个是 if (current.right != null)?
猜你喜欢
  • 2020-02-21
  • 1970-01-01
  • 2012-01-26
  • 2015-08-31
  • 2018-05-03
  • 2014-08-12
  • 2019-12-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多