現在、並べ替えられたリンク リストがあり、void リターン メソッドを使用して、リスト (2 番目のパラメーターと呼ばれます) からバランスのとれた二分探索木を再帰的に構築する必要があります。パラメータとして、LL ヘッド、作成されるルート、およびリストの長さのみを指定できます。
このメソッドは LL に対して破壊的であってはならず、後でツリーをテストするために、printTree と 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;
}