【问题标题】:Best practice to build a BST from a Binary Tree从二叉树构建 BST 的最佳实践
【发布时间】:2021-02-19 10:14:09
【问题描述】:

我在 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 根(而不是 BinaryTree.Node 根),因此当我从 BST 调用在 BinaryTree 中实现的 print 时,打印 null :/

所以我的问题是:

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

【问题讨论】:

    标签: java inheritance binary-search-tree inner-classes


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-12-15
      • 2021-01-31
      • 2020-09-03
      • 2013-01-08
      • 1970-01-01
      • 2014-07-09
      • 2015-09-20
      • 1970-01-01
      • 2021-09-28
      相关资源
      最近更新 更多