【发布时间】:2014-12-26 22:42:54
【问题描述】:
您好,我正在寻找一种将树的位置递归分配给 int 索引的方法,以便可以将位置处的节点的值放入数组中。
所需的树位置按级别顺序指定,其中根位置为 1 (i),i 的左子节点位于位置 2i,右子节点位于 2i + 1 - 类似于堆结构。 Null 子节点不会获得分配给他们的位置。
1
/ \
2 3
/\ /\
4 5 6 7
...
[1, 2, 3, 4, 5, 6, 7. ...]
而树中最大的位置应该是数组的大小。我的输出需要添加空值作为“空格”来测试节点值。
private int largestPos
// first call: assignPositions(root, 1)
assignPositions(node cur, int pos) {
parent = new node;
if curpos > largestPos
largestPos = curPos
if cur == null
parent.pos = pos
else
current.pos = pos
parent = cur
if cur.left != null
pos = 2 * pos
assignPositions(cur.left, pos)
if cur.right != null
pos = 2 * pos + 1
assignPositions(cur.right, pos)
}
当我尝试打印我的数组时,我得到前两个值被正确分配,然后一大块没有值的空值(在树中确认)不在树中。
我希望这样做是为了找出在树中删除后我需要的最小数组大小。
更新广度优先搜索数组:
public Key[] breadthFirstTraversal() {
@SuppressWarnings("unchecked")
Key[] keysFinal = new Key[largestPos];
List<Key> queue = new List<Key>();
List<Key> keysList = new List<Key>();
List<Integer> positions = new List<Integer>();
if (!isEmpty()) {
Node tempNode = root;
KeyValuePair<Key, Value> tempKey = null;
queue.add(tempNode);
while (!queue.isEmpty()) {
queue.reset();
tempKey = queue.remove();
keysList.add(tempKey);
tempNode = findKey(tempKey.getKey(), root);
// adds keys in order on level in list
if (tempNode.getLeftChild() != null) {
queue = addAtEnd(queue, tempNode.getLeftChild());
}
if (tempNode.getRightChild() != null) {
queue = addAtEnd(queue, tempNode.getRightChild());
}
}
for (int i = 1; i < largestPos + 1; i++) {
keysList.reset();
tempKey = keysList.remove();
tempNode = findKey(, root);
if (tempNode.getPosition() == i) {
keysFinal[i - 1] = tempKey;
} else {
keysFinal[i - 1] = null;
}
}
}
return keysFinal;
}
【问题讨论】:
-
处理树的正常递归方式在这里不起作用。我认为您要做的是在处理 1 级时,保留要处理的 2 级节点的“待办事项”列表。然后遍历这个列表,在处理它的同时,保留一个 3 级节点的“待办事项”列表。然后,当您完成第 2 级时,请查看第 3 级节点的列表等。或者您可以将所有内容放在一个队列中。在 Wikipedia 中查找“树遍历”并向下滚动到“广度优先搜索”。
-
@ajb 我添加了我当前的广度优先搜索。