【发布时间】:2016-03-03 18:06:05
【问题描述】:
我参考了许多帖子和答案,但仍然无法获得有效的代码。下面是java中BST的排序链表代码。包含链表的所有辅助函数。
我得到的输出不是预期的,即 root : 4 , root.left 是 2 并且 root.right 又是 4 。我想输出应该是 root : 4 , root.left 是 2 而 root.right 是 6
class LNode {
public int data;
public LNode next;
LNode(int newData) {
this.data = newData;
}
}
class Node {
int data;
Node left;
Node right;
public Node prev;
Node(int d) {
data = d;
left = right = null;
}
}
class LinkedList {
LNode first;
LNode head;
LNode newNode;
public LinkedList() {
first = null;
}
public void insertAtBeginning(int x) {
newNode = new LNode(x);
if (first != null) {
newNode.next = first;
first = newNode;
head = first;
} else {
first = newNode;
head = first;
}
}
public void printList()
{
head = first;
while (first != null) {
System.out.print(first.data + " --> ");
first = first.next;
}
System.out.println("null");
first = head;
}
}
public class LLtoBST {
public static Node root;
//public static LNode first;
public static Node sortedListToBST(LNode first, int end) {
return sortedListToBST(first, 0, end);
}
public static Node sortedListToBST(LNode first, int start, int end) {
if (start > end)
return null;
if (first != null) {
int mid = start + (end - start) / 2;
Node lnode = sortedListToBST(first, start, mid - 1);
root = new Node(first.data);
first = first.next;
Node rnode = sortedListToBST(first, mid + 1, end);
root.left = lnode;
root.right = rnode;
}
return root;
}
public static void main(String... args) {
LinkedList list = new LinkedList();
int n = 0;
list.insertAtBeginning(7);
list.insertAtBeginning(6);
list.insertAtBeginning(5);
list.insertAtBeginning(4);
list.insertAtBeginning(3);
list.insertAtBeginning(2);
list.insertAtBeginning(1);
list.printList();
first = list.head;
while (first != null) {
n++;
first = first.next;
}
first = list.head;
Node curr = sortedListToBST(first, n);
System.out.println(curr.data);
System.out.println(curr.left.data);
System.out.println(curr.right.data);
}
}
Output :
1 --> 2 --> 3 --> 4 --> 5 --> 6 --> 7 --> null
4
2
4
任何帮助将不胜感激。
【问题讨论】:
标签: java data-structures binary-search-tree recursive-datastructures