binary search tree impelementation and java

前端 未结 6 668
离开以前
离开以前 2021-01-03 09:10

I am trying to implement BST algorithm using Cormen\'s pseudo code yet having issue.

Here is my Code for Node:

public class Node {
    Node left;
            


        
6条回答
  •  孤街浪徒
    2021-01-03 09:20

    As per my understanding following implementation done for binary search tree, kindly look into that and let me know any feedback required

    1. Insertion
    2. InOrderTraversal
    3. Search
    4. Removal

    Please take a look at the main method. so, Please provide your's feedback to improve further from my side.

    public class BinarySearchTree {
    
        private Node root;
    
        public  BinarySearchTree() {
            root = null;        
        }
        public BinarySearchTree(int rootData) {
            root = new Node(rootData);
        }
    
        public void insertElement(int element,Node parent) {
    
            Node temp = root;
            if(parent!=null) temp = parent;
    
            if(temp!=null) {
                Node node = new Node(element);
                if(elementtemp.getData()) {              
                    if(temp.getRight()!=null)
                        insertElement(element, temp.getRight());
                    else
                        temp.setRight(node);
                }
            }
        }
    
    
        public void traverseInOrder() {
            if(root!=null) {
                traverse(root.getLeft());
                System.out.println(root.getData());
                traverse(root.getRight());
            }
        }
    
        public void traverse(Node temp) {       
            if(temp!=null) {
                traverse(temp.getLeft());
                System.out.println(temp.getData());
                traverse(temp.getRight());
    
            }
        }
    
        public int searchElement(int element,Node node) {
    
            Node temp = root;
            if(node!=null) temp = node;
            if(temp!=null) {
                if(temp.getData()element) {
                    if(temp.getLeft()!=null)
                        return searchElement(element,temp.getLeft());
                }else if(temp.getData()==element){
                    return temp.getData();
                }
            }
            return -1;
        }
    
    
        public void remove(int element,Node node,Node predecer) {
    
            Node temp = root;
            if(node!=null) temp = node;
    
            if(temp!=null) {
                if(temp.getData()>element) {
                    remove(element, temp.getLeft(), temp);
                }else if(temp.getData()temp.getData()) {
                            predecer.setLeft(null);
                        }else if(predecer.getData()

提交回复
热议问题