【发布时间】:2016-08-16 13:26:36
【问题描述】:
我想创建一个 BST,它在插入元素时会在完美平衡的树中返回它的索引。例如(括号中的数字表示实际索引):
5(1)
/ \
/ \
3(2) 6(3)
/
2(4)
或
1(1)
\
\
2(3)
\
\
3(7)
在第二个例子中,我们可以看到元素 1 没有左孩子,但元素 2 的索引仍然为 3,就像在完美平衡的树中一样。
根节点以1开头。
在插入时返回索引的有效方法是什么?
现在在 BST 中插入一个元素,我的代码如下:
Node newNode = new Node(id);
if(root==null){
root = newNode;
return 1;
}
Node current = root;
Node parent = null;
while(true){
parent = current;
if(id<current.data){
current = current.left;
if(current==null){
parent.left = newNode;
return;
}
}else{
current = current.right;
if(current==null){
parent.right = newNode;
return;
}
}
}
我不明白我应该如何保持元素被插入到哪个级别来计算索引。
可以插入的元素数量最大为 3*10^5。存储在数组中获取索引不会是一种有效的方法
【问题讨论】:
标签: java algorithm binary-search-tree