【发布时间】: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