Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

bst in java

import java.util.*;
import java.io.*;
 
class GFG {
    public static void main (String[] args) {
         BST tree=new BST();
        tree.insert(30);
        tree.insert(50);
        tree.insert(15);
        tree.insert(20);
        tree.insert(10);
        tree.insert(40);
        tree.insert(60);
        tree.inorder();
    }
}
 
class Node{
    Node left;
    int val;
    Node right;
    Node(int val){
        this.val=val;
    }
}
 
class BST{
  Node root;
   
  public void insert(int key){
        Node node=new Node(key);
        if(root==null) {
            root = node;
            return;
        }
        Node prev=null;
        Node temp=root;
        while (temp!=null){
            if(temp.val>key){
                prev=temp;
                temp=temp.left;
            }
            else if (temp.val<key){
                prev=temp;
                temp=temp.right;
            }
        }
        if(prev.val>key)
            prev.left=node;
        else prev.right=node;
    }
   
   public void inorder(){
        Node temp=root;
        Stack<Node> stack=new Stack<>();
        while (temp!=null||!stack.isEmpty()){
            if(temp!=null){
                stack.add(temp);
                temp=temp.left;
            }
            else {
                temp=stack.pop();
                System.out.print(temp.val+" ");
                temp=temp.right;
            }
        }
    }
}
Comment

PREVIOUS NEXT
Code Example
Java :: set textView.android:drawableEnd programmatically 
Java :: find minimum number in java 
Java :: how to change checkbox color in android 
Java :: gradle could not determine java versionAdd Answer 
Java :: which api is android 12 
Java :: java for loop increment by 3 
Java :: close keyboard android 
Java :: make edittext not editable android 
Java :: java wait for user input 
Java :: longest common subsequence of two strings 
Java :: has been compiled by a more recent version of the Java Runtime (class file version ), this version of the Java Runtime only recognizes class file versions up to 
Java :: spring boot MVC config 
Java :: method resolve file in java 
Java :: I/flutter (10109): {filePath: null, errorMessage: java.io.FileNotFoundException: open failed: EACCES (Permission denied), isSuccess: false} 
Java :: java what is at 
Java :: json array to list in java 
Java :: Java Sorting Using sort() 
Java :: convert string into time in java 
Java :: constraintlayout vs coordinatorlayout 
Java :: apache csv get headers 
Java :: Java alt f4 
Java :: java enum 
Java :: spring boot get request body 
Java :: keytool error: java.lang.Exception: Key pair not generated, alias <demo already exists 
Java :: quarkus skip test 
Java :: Cannot find a class with the main method. 
Java :: reverse number in java 
Java :: hashmap in java 
Java :: java array sorting java8 
Java :: java methods 
ADD CONTENT
Topic
Content
Source link
Name
6+5 =