linkedList
に変換するために私が書いた主要なメソッドを次に示しますBalanced BinarySearch Tree
。わかりますBST
が、バランスが取れていません。なぜそうなのですか?
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;
}
主な方法は次のとおりです。
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);
これが私が得る出力です(読みやすいようにフォーマットされています):
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]
レベルの順序と preOrder が一致しないため、一意のツリーが構築されます。ここにヒントはありますか?