Advertisement
korobushk

insertBST

May 20th, 2021
646
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.92 KB | None | 0 0
  1. import java.util.*;
  2. import java.io.*;
  3.  
  4. class Node {
  5.     Node left;
  6.     Node right;
  7.     int data;
  8.    
  9.     Node(int data) {
  10.         this.data = data;
  11.         left = null;
  12.         right = null;
  13.     }
  14. }
  15.  
  16. class Solution {
  17.    
  18.     public static void preOrder( Node root ) {
  19.      
  20.         if( root == null)
  21.             return;
  22.      
  23.         System.out.print(root.data + " ");
  24.         preOrder(root.left);
  25.         preOrder(root.right);
  26.      
  27.     }
  28.  
  29.  /* Node is defined as :
  30.  class Node
  31.     int data;
  32.     Node left;
  33.     Node right;
  34.    
  35.     */
  36.  
  37.     public static Node insert(Node root,int data) {
  38.         if(root == null){
  39.          Node newNode = new Node(data);
  40.             return newNode;
  41.         }else if(data<=root.data){
  42.             root.left = insert(root.left,data);
  43.             return root;
  44.         }else {
  45.             root.right = insert(root.right,data);
  46.             return root;
  47.         }
  48.    
  49.     }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement