[英]Uniquely number nodes of a Binary Tree
生成二叉树后,如何为每个节点设置索引?
(a) (1)
(x) (r) => (2) (3)
(o)(t)(t)(x) (4)(5)(6)(7)
因此,我可以在特定节点上使用诸如getIndex()
类的调用来返回其索引。
我的树类:
public class BT<E>{
E value;
BT<E> left, right;
int Index;
public BT(E value)
{
this.value=value;
}
public BT (E value, BT left, BT right)
{
this.value = value;
this.left = left;
this.right = right;
}
广度优先遍历。
Queue<BT> queue = new LinkedList<BT>() ;
public void breadth(BT root) {
if (root == null)
return;
queue.clear();
queue.add(root);
int index = 0;
while(!queue.isEmpty()){
BT node = queue.remove();
node.Index = index;
index++;
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
}
}
从这里改编。
因此,您要实现一个过程getIndex(int index)
,该过程必须返回具有该索引的节点?
如果是这样,您正在寻找一种表示二叉树的有效方法。 您可以遍历每次调用getIndex
的树,但这效率不高...
一种有效的解决方案是将完整的二叉树存储在数组中,因为它提供了O(1)访问。 将节点n存储在数组中的索引n处,并将其子节点存储在索引2*n
和(2*n) - 1
。 但是这里的限制是树必须是完整的,并且数组的大小不能改变(如果二进制树太大,则应制作更大的数组(通常是两倍大),并应复制所有元素)。
这是一个方便的解决方案,因为:
addNode()
的过程将在O(1)中摊销 。 (*) this.left
变成this.left()
,下面提供了left()
的实现。 left()
过程的可能实现。
static int[] binaryTreeArray = new int[maxTreeSize]; // BT of integers for example
...
public int left() { // returns integer or ... (type of your nodes)
return binaryTreeArray[(this.Index)*2]; // O(1)
}
(*) binaryTreeArray[index] = nodeValue;
addNode()
的过程binaryTreeArray[index] = nodeValue;
会在O(1)中添加节点( binaryTreeArray[index] = nodeValue;
),但是当binaryTreeArray
充满时,它必须制作一个更大的数组,通常是两倍大。大(用于复制的O(n))。 可以证明,这具有O(1)的摊销成本,但是此答案没有附加值。
如果您在树完全创建后执行此操作,则可以使用使用级别顺序遍历的方法。 这并不是非常有效,但是它是直接递归的:
/* Method to set index based on level-order traversal of tree */
public void initIndices(BT root) {
int maxIndexSoFar = 0;
for (int d = 1; d <= root.height(); ++d)
maxIndexSoFar = setIndexAtLevel(root, d, maxIndexSoFar);
}
/* Method to set index of all nodes at a given level */
private int setIndexAtLevel(BT node, int level, int index) {
if (tree == null)
return index;
if (level == 1) {
index++;
node.setIndex(index);
return index;
}
else if (level > 1) {
int newIndex = setIndexAtLevel(node.left, level-1, index);
newIndex = setIndexAtLevel(node.right, level-1, newIndex);
return newIndex;
}
return -1;
}
我将让您创建height()
方法和setIndex()
方法。 公平的警告,我根本没有测试过,因此请避免任何错别字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.