简体   繁体   English

在二叉树的节点类中递归

[英]Recurse within binary tree's node class

I have successfully written a method to print the values of all the nodes in the subtree rooted at a given node (code pasted below under the label "Working Code"). 我已经成功地编写了一种方法来打印以给定节点为根的子树中所有节点的值(以下代码粘贴在标签“工作代码”下)。 However, this printTree method is in the Main class (as opposed to being in the Node class itself). 但是,此printTree方法在Main类中(而不是在Node类本身中)。 I am wondering if it is possible (and ideal?) to rewrite the code so that the printTree method is in the Node class itself? 我想知道是否有可能(并且是理想的方法)重写代码,以使printTree方法位于Node类本身中? My attempt is below (code pasted below under the label "Non Working Code"), but it threw a Null Pointer Exception. 我的尝试在下面(代码粘贴在下面的“非工作代码”标签下),但是它抛出了空指针异常。 Thank you! 谢谢!

WORKING CODE: 工作代码:

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);

    }
}

NON WORKING CODE (in Node class): 非工作代码(在Node类中):

public void printTree()
{
    Node current = this;

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

    return;
}

The problem is not in the Node current = this; 问题不出在Node current = this; line. 线。 But in the 但是在

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

lines. 线。

Because even when current is not null, current.left or current.right could be null. 因为即使current不为null,current.left或current.right也可能为null。 And you are trying to invoke printTree() on a null object. 并且您试图在null对象上调用printTree()

Fix: 固定:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM