递归地向 BST 添加一个项目

recursively adding an item to the BST

我正在尝试制作一种将项目添加到树中的方法,然后我想将这棵树打印到控制台。我有一个继承的 class,基于它我需要编写我需要的方法:

public abstract class BinaryTreeNode {
    protected int data; // value stored in the node
    protected BinaryTreeNode left, right; // left and right sub-trees

    // constructor
    public BinaryTreeNode(int data) {
        this.data = data;
    }

    // recursively adds an item to the BST
    // @param new data to be stored in the new node
    public abstract void addBSTRecursion(int newNode);

    // prints the tree
    // for example, for a tree:
    //        7
    //    6        8
    // 2     7  4     9
    //
    // write:
    //
    //      2
    //   6
    //      7
    // 7
    //      4
    //   8
    //      9

    // method pseudocode
    //if there is a left subtree then print the left one (recursive call)
    //write out gaps (depending on level), write out data, go to new line
    //if it is right, print the right one (recursive call)
    //@param level the distance of the node from the root. We start from 0.
    public abstract void print(int level);

}

addBSTRecursion(int newNode) - 递归地添加一个项目到 BST
print(int level) - 如果有左子树,则打印左子树(递归调用),写出间隙(取决于级别),写出数据,转到新行,如果正确,则打印右子树(递归调用) 这是我设法做到的:

public class Node extends BinaryTreeNode {
    public Node(int data) {
        super(data);
    }

    @Override
    public void addBSTRecursion(int newNode) {
        if (data < this.data) {
            if (left != null) {
                left.addBSTRecursion(newNode);
            } else {
                left = new Node(newNode);
            }
        } else {
            if (right != null) {
                right.addBSTRecursion(newNode);
            } else {
                right = new Node(newNode);
            }
        }
    }

    @Override
    public void print(int level) {
        if(this.left != null)this.left.print(level+1);
        for(int n =0; n<level; n++) System.out.print(" ");
        System.out.println(data);
        if(this.right != null)this.right.print(level+1);
    }
}

我的输出:

10
 5
  14

我想收到:

   5
10
   14

这总是 false,因为它将 this.data 与自身进行比较:

    if (data < this.data) {

应该是:

    if (newNode < this.data) {

注意:调用参数 newNode 是一种误导,因为它不是 Node 类型,而是一个整数。也许叫它 newData.