简体   繁体   English

递归插入二叉搜索树JAVA

[英]Recursive insert binary search tree JAVA

I have this code and I'm finding difficulties to write it in a recursive way (insert method in Binary search tree)我有这段代码,我发现以递归方式编写它很困难(在二叉搜索树中插入方法)

    public void insert(E element){
        BTNode<E> node=root;
        boolean stop=false;
        while(!stop){
            if(element.compareTo(node.getElement())<0){
                if(node.getLeft()==null){
                    node.setLeft(new BTNode<E>(element));
                    stop=true;
                } else{
                    node=node.getLeft();
                }
            }
            else{
                if(node.getRight()==null){
                    node.setRight(new BTNode<E>(element));
                    stop=true;
                } else{
                    node=node.getRight();
                }
            }
                
        }
        
    }

You could write a method that accepts the root and the element to be inserted and returns the modified root.您可以编写一个方法来接受根和要插入的元素并返回修改后的根。

public BTNode<E> insert(BTNode<E> root, E element) {
   if ( root == null ) {
      root = new BTNode<E>(element);
   } else if ( element.compareTo(root.getElement()) < 0 ) {
      root.left = insert(root.left, element);
   } else {
      root.right = insert(root.right, element);
   }
   return root;
}

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

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