以下是我为转换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 不匹配构建唯一树。这里有什么提示吗?