Monday, August 17, 2015

Construct BST from PreOrder traversal array

Problem

Given an preorder traversal array as input, reconstruct a binary search tree.

Solution

public class Tree {
 public int node;
 public Tree left;
 public Tree right; 
}

public class TreeProblem1 extends Tree{
 int index = 0;
 Tree construct(int[] pre, int min, int max)
 {
  if(index>=pre.length) return null;
  if(pre[index]>max || pre[index] < min) return null;
  Tree t = new Tree();
  t.node = pre[index++];
  t.left = construct(pre,min, t.node);
  t.right = construct(pre, t.node, max);
  return t;
 }
 
 Tree reContructTree(int[] preorder)
 {
  index = 0;
  return construct(preorder, Integer.MIN_VALUE, Integer.MAX_VALUE);
 }
 
 public static void main(String[] args) {
  
  int[] pre = {10,5,1,2,7,50,100};
  TreeProblem1 ob = new TreeProblem1();
  Tree t = ob.reContructTree(pre);
  TreeOperations.printTree(t);
 }

}

No comments:

Post a Comment