LoganBlackisle

BST_construct

Jun 16th, 2019
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. package prep_33_binarysearchtrees;
  2.  
  3. public class BST_construct {
  4. // A binary tree node
  5. public class Node {
  6. int data;
  7. Node left, right;
  8.  
  9. Node(int d) {
  10. data = d;
  11. left = right = null;
  12. }
  13. }
  14.  
  15. public class Index {
  16. int index = 0;
  17. }
  18.  
  19. public class BinaryTree {
  20. Index index = new Index();
  21.  
  22. // A recursive function to construct BST from pre[]. preIndex is used
  23. // to keep track of index in pre[].
  24. public Node constructTreeUtil(int pre[], Index preIndex, int key, int min, int max, int size) {
  25.  
  26. // Base case
  27. if (preIndex.index >= size) {
  28. return null;
  29. }
  30.  
  31. Node root = null;
  32.  
  33. // If current element of pre[] is in range, then
  34. // only it is part of current subtree
  35. if (key > min && key < max) {
  36.  
  37. // Allocate memory for root of this
  38. // subtree and increment *preIndex
  39. root = new Node(key);
  40. preIndex.index = preIndex.index + 1;
  41.  
  42. if (preIndex.index < size) {
  43.  
  44. // Contruct the subtree under root
  45. // All nodes which are in range {min .. key}
  46. // will go in left subtree, and first such
  47. // node will be root of left subtree.
  48. root.left = constructTreeUtil(pre, preIndex, pre[preIndex.index], min, key, size);
  49.  
  50. // All nodes which are in range {key..max}
  51. // will go in right subtree, and first such
  52. // node will be root of right subtree.
  53. root.right = constructTreeUtil(pre, preIndex, pre[preIndex.index], key, max, size);
  54. }
  55. }
  56. return root;
  57. }
  58.  
  59. // The main function to construct BST from given preorder traversal.
  60. // This function mainly uses constructTreeUtil()
  61. public Node constructTree(int pre[], int size) {
  62. return constructTreeUtil(pre, index, pre[0], Integer.MIN_VALUE, Integer.MAX_VALUE, size);
  63. }
  64.  
  65. // A utility function to print inorder traversal of a Binary Tree
  66. public void printInorder(Node node) {
  67. if (node == null) {
  68. return;
  69. }
  70. printInorder(node.left);
  71.  
  72. System.out.print(node.data + " ");
  73.  
  74. printInorder(node.right);
  75. }
  76. }
  77. }
Add Comment
Please, Sign In to add comment