Languages [3i Infotech Placement]: Sample Questions 444 - 444 of 546

Glide to success with Doorsteptutor material for competitive exams : get questions, notes, tests, video lectures and more- for all subjects of your exam.

Question 444

Languages
Edit

Describe in Detail

Essay▾

Write down how will you create a binary tree?

Explanation

Binary tree have an elegant recursive pointer structure allowing recursive pointer algorithms.

Code of binary search tree:

  1. classBinarySearchTree
  2. {
  3.     classNode
  4.     {
  5.         intkey;
  6.         Nodeleft, right;
  7.         publicNode(intitem) {
  8.             key =item;
  9.             left =right =null;
  10.         }
  11.     }
  12.     Noderoot;
  13.     BinarySearchTree()
  14.     {
  15.         root =null;
  16.     }
  17.     voidinsert(intkey)
  18.     {
  19.         root =insertRec(root, key);
  20.     }
  21.     NodeinsertRec(Noderoot, intkey)
  22.     {
  23.         if (root == null)
  24.         {
  25.             root =newNode(key);
  26.             returnroot;
  27.         }
  28.         if (key <root.key)
  29.         root.left =insertRec(root.left, key);
  30.         elseif (key >root.key)
  31.         root.right =insertRec(root.right, key);
  32.         returnroot;
  33.     }
  34.     voidinorder()
  35.     {
  36.         inorderRec(root);
  37.     }
  38.     voidinorderRec(Noderoot)
  39.     {
  40.         if (root !=null)
  41.         {
  42.             inorderRec(root.left);
  43.             System.out.println(root.key);
  44.             inorderRec(root.right);
  45.         }
  46.     }
  47.     publicstaticvoidmain(String[] args)
  48.     {
  49.         BinarySearchTreetree =newBinarySearchTree();
  50.         tree.inorder();
  51.     }
  52. }

Output:

Insert data: 50, 30, 20, 40,70, 60,80

Output: 20, 30, 40, 50, 60,70, 80

Developed by: