I currently have a sorted Linked List, and with a void return method, I need to recursively construct a balanced binary search tree from the list (which is referred to as the second parameter). And as parameters I can have only the LL Head, the root being created, and the length of the list.
The method cannot be destructive to the LL, and to test the tree afterwards I have a printTree and a treeDepth:
public static void makeBalancedTree(ListNode head, TreeNode root, int count)
{
//here
}
public static void printTree(TreeNode root)
{
if(root != null)
{
//Print recursive left, center, recursive right
printTree(root.left);
System.out.print(root.data + " ");
printTree(root.right);
}
}
public static int depth(TreeNode root)
{
if (root == null)
return -1;
int deep;
//Return larger of the two subtree's depths, +1
deep = Math.max(depth(root.right), depth(root.left));
return deep+1;
}
public static int countList(ListNode head)
{
int count = 0;
ListNode cursor = new ListNode();
cursor = head;
while (cursor.link != null)
{
cursor = cursor.link;
++count;
}
return count;
}