Advertisement
Unit2

Tree

Feb 25th, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.82 KB | None | 0 0
  1. package main;
  2.  
  3. public class Tree {
  4.  
  5.     class Node
  6.     {
  7.         int key;
  8.         Node left;
  9.         Node right;
  10.        
  11.         public Node(int item)
  12.         {
  13.             key = item;
  14.             right = null;
  15.             left = null;
  16.         }
  17.     }
  18.    
  19.     Node root;
  20.    
  21.     Tree()
  22.     {
  23.         root = null;
  24.     }
  25.    
  26.     void insert(int key)
  27.     {
  28.         root = insertRec(key, root);
  29.     }
  30.    
  31.     Node insertRec(int key, Node root)
  32.     {
  33.         if (root == null)
  34.         {
  35.             root = new Node(key);
  36.            
  37.             return root;
  38.         }
  39.        
  40.         if (key < root.key)
  41.         {
  42.             root.left = insertRec(key, root.left);
  43.         }
  44.        
  45.         else
  46.         {
  47.             root.right = insertRec(key, root.right);
  48.         }
  49.        
  50.         return root;
  51.     }
  52.    
  53.     void inorder()
  54.     {
  55.         inorderRec(root);
  56.     }
  57.    
  58.     void inorderRec(Node root)
  59.     {
  60.         if (root != null)
  61.         {
  62.             inorderRec(root.left);
  63.            
  64.             System.out.print(" " + root.key + " ");
  65.            
  66.             inorderRec(root.right);
  67.         }
  68.            
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement