Java 从二叉树构建BST的最佳实践

Java 从二叉树构建BST的最佳实践,java,inheritance,binary-search-tree,inner-classes,Java,Inheritance,Binary Search Tree,Inner Classes,我正在用Java创建一个二叉搜索树,它是从一个已经实现的二叉树扩展而来的,但是当我尝试使用一些继承的方法时,它不起作用。让我解释一下: 二叉树: public class BinaryTree<T>{ private Node<T> root; public class Node<T>{ T value; Node left; Node right; pub

我正在用Java创建一个二叉搜索树,它是从一个已经实现的二叉树扩展而来的,但是当我尝试使用一些继承的方法时,它不起作用。让我解释一下:

二叉树:

public class BinaryTree<T>{
     private Node<T> root;

     public class Node<T>{
          T value;
          Node left;
          Node right;

          public Node(T value){
               this.value = value;
               this.left = null;
               this.right = null;
          }
     }
     
     public BinaryTree(){
          ...
     }
     public void printInOrder(){
          ...
     }  
 }
public class BST extends BinaryTree<Integer>{
      private Node<Integer> root;

      public BST(Integer v){
          super(v);
      }

      public void insert(Integer element){
            insert(this.root, element);
      }

      private insert( Node node, Integer element){
            if(node == null)
               return;
        
            if(node.value > value) {
                  if(node.left != null) {
                       insert(node.left, value);
                  }
                  else {
                       node.left = new NodeBST(value);
                  }
             }else { // Node.value < element
                 if(node.right != null) {
                      insert(node.right, value);
                 }
                 else {
                      node.right = new NodeBST(value);
                 }
             }

         }

   }
public class App{

      public static void main(String[] args){
             BST bst = new BST(4);
             bst.insert(2);
             bst.insert(5);
             bst.insert(3);
             bst.insert(7);

             bst.printInOrder();  //Here I got the problem

     }
}
如果我尝试打印它,它将只打印根(4),其余节点将为空。当我看看里面发生了什么,结果发现有两个根源:

  • BST.Node root,它按正确顺序包含所有节点
  • BinaryTree.Node root,它只包含根,所有其他节点为空
因此,我猜它正确地创建了根,因为我在BST的构造函数中调用了超类,但当我在insert方法中创建新节点时,它只将其追加到BST.Node root(而不是BinaryTree.Node root)中,因此当我在prints null中从BST调用print(在BinaryTree中实现)时:/

所以我的问题是:

  • 如何从BST使用print方法来打印BST.Node root中的所有值
  • 是什么阻止BinaryTree.Node根与BST.Node根相同
  • 这样做的最佳做法是什么

    • 不要在BST中再次声明“root”,它会在基类中隐藏“root”

      要么在BinaryTree中保护“root”,要么在那里提供必要的访问器,以便子类可以使用它