Here are key methods I wrote for converting linkedList
to Balanced BinarySearch Tree
. I get BST
but it is not balanced. why is it so?
public static Node headNode;
public static IntTreeNode convertLinkedListToBST(Node node){
int len = getCount(node);
headNode = node;
return convertLinkedListToBSThelper(node, 0, len-1);
}
//http://www.programcreek.com/2013/01/leetcode-convert-sorted-list-to-binary-search-tree-java/
public static IntTreeNode convertLinkedListToBSThelper(Node node, int start, int end) {
if (start>end)
return null;
int mid=start+end >>1 ;
IntTreeNode left = convertLinkedListToBSThelper(node, start, mid-1);
IntTreeNode root = new IntTreeNode(headNode.data);
headNode=headNode.next;
IntTreeNode right = convertLinkedListToBSThelper(node, mid+1, end);
root.left=left;
root.right=right;
return root;
}
private static int getCount(Node node){
int count=0;
Node current = node;
while(current!=null){
current=current.next;
count++;
}
return count;
}
Here is main method:
Node node = new Node(1);
node.next=new Node(2);
node.next.next=new Node(3);
node.next.next.next=new Node(4);
node.next.next.next.next=new Node(5);
node.next.next.next.next.next=new Node(6);
node.next.next.next.next.next.next=new Node(7);
node.next.next.next.next.next.next.next=new Node(8);
System.out.println("***********");
IntTreeNode result1 = convertLinkedListToBST(node);
System.out.println("preOrder");
printPreOrder(result1);
System.out.println("inOrder");
printInOrder(result1);
System.out.println("postOrder");
printPostOrder(result1);
System.out.println();
System.out.println(isValidBST(result1));
List<Integer> list = new ArrayList<>();
printLevelorder(result1, list);
System.out.println(list);
Here is the output I get (formatted for readability):
preOrder 4, 1, 2, 3, 5, 6, 7, 8,
inOrder 1, 2, 3, 4, 5, 6, 7, 8,
postOrder 1, 2, 3, 5, 6, 7, 8, 4,
true
[4, 2, 6, 1, 3, 5, 7, 8]
Level order and preOrder does not match to build a unique tree. Any tips here ?
Your convertLinkedListToBSThelper & getcount method work well.I have used your both method in my code.
I think you are doing mistake in some traversal method. Please check it out with mine.Still if you have problem just paste whole code. btw my code gives output
One more thing there is always unique binary tree(may be balance BST or BST) with given following combination