2017-06-25 53 views
1

让结构由下式给出遍历N叉树级订单

/*      1 
    *   /---------|--------\ 
    *   2   3   4 
    *  / \    /
    *  5  6    7 
    */ 

它返回

Node val: 1 
Node val: 2 
Node val: 3 
Node val: 4 
Node val: 5 
Node val: 4 
Node val: 7 
Node val: 6 
Node val: 7 

但预期是1 2 3 4 5 6 7我已经双带预,位置和为了横向的功能检查,所有这些返回正确,如下:

PRE 1 2 _5 _6 _3 4 _7 

POS _5 _6 2 _3 _7 4 1 

IN _5 2 _6 1 _3 _7 4 

寻找找出可能会误导我在我的功能

+0

'而{ 头= dequeueLL(队列); if(head){':: ...这看起来像Java。 – wildplasser

+0

@wildplasser很奇怪,编译我的GCC很好。 :-) – Lin

+0

这是关于风格。你可以用四条线来完成其中一条。 – wildplasser

回答

2

当您访问一个节点时,您将排队后面的所有兄弟姐妹。下一个兄弟会再次排队其余的兄弟姐妹。如果你有才能把元素添加到队列的开始操作,您可以使用入队的孩子

if (sibling) { 
    pushLL(queue, sibling); 
} 

或者只是排队的孩子,而不是兄弟姐妹,这是通常的方式,使对于更短的函数:(!isQueueEmptyLL(队列))

void nNode_traverse_levelOrder(struct nNode* node) { 
    struct QueueLL* queue = newQueueLL(); 

    enqueueLL(queue, node); 

    while (!isQueueEmptyLL(queue)) { 
    struct nNode* head = dequeueLL(queue); 

    visit(head); 

    for (struct nNode* child = head->children; child != NULL; child = child->next) { 
     enqueueLL(queue, child); 
    } 
    } 

    destroyQueueLL(queue); 
} 
+0

(编辑风暴后;-)第一种方法是可行的,但我需要在我的队列中做一些小改动(简单的改变)。第二种方法看起来非常合理,但它返回1 2 3 4 5 7 6(试图找出原因)。第三个运行正常。 (详细阅读)。 – Lin

+0

*他们对伟大思想的评价* – wildplasser