這看起來像是我在25年前在工程學院所做的練習。 我認爲這被稱爲樹包絡算法,因爲它繪製了樹的包絡。
我不敢相信它那麼簡單。我一定在某個地方犯了一個無知的錯誤。 不管怎麼樣,我相信包封策略是正確的。 如果代碼是錯誤的,只要將其視爲僞代碼即可。
while current node exists{
go down all the way until a leaf is reached;
set current node = leaf node;
visit the node (do whatever needs to be done with the node);
get the next sibling to the current node;
if no node next to the current{
ascend the parentage trail until a higher parent has a next sibling;
}
set current node = found sibling node;
}
代碼:
void traverse(Node* node){
while(node!=null){
while (node->child!=null){
node = node->child;
}
visit(node);
node = getNextParent(Node* node);
}
}
/* ascend until reaches a non-null uncle or
* grand-uncle or ... grand-grand...uncle
*/
Node* getNextParent(Node* node){
/* See if a next node exists
* Otherwise, find a parentage node
* that has a next node
*/
while(node->next==null){
node = node->parent;
/* parent node is null means
* tree traversal is completed
*/
if (node==null)
break;
}
node = node->next;
return node;
}
一個字......堆棧。 – ChaosPandion 2010-07-09 15:54:10
按什麼順序? – kennytm 2010-07-09 15:54:20
任何順序,最好是深度優先 – uray 2010-07-09 15:56:12