问题
I want to perform level-order traversal of a binary tree. Hence, for a given tree, say:
3
/ \
2 1
/ \ \
4 6 10
the output would be:
3 2 1 4 6 10
I understand that I could use some sort of queue, but what is the algorithm to do this in C recursively? Any help appreciated.
回答1:
The graph algorithm is called Breadth First Search, it uses a queue to perform the level-order traversal, here is the pseudo-code
void breadth_first(Node root)
{
Queue q;
q.push(root);
breadth_first_recursive(q)
}
void breadth_first_recursive(Queue q)
{
if q.empty() return;
Node node = q.pop()
print Node
if (n.left) q.push(n.left)
if (n.right) q.push(n.right)
breadth_first_recursive(q)
}
回答2:
here to you the pseudocode from wikipedia
levelorder(root)
q = empty queue
q.enqueue(root)
while not q.empty do
node := q.dequeue()
visit(node)
if node.left ≠ null
q.enqueue(node.left)
if node.right ≠ null
q.enqueue(node.right)
you can then transform it into C that is trivial...
回答3:
Here code (no recursive function) from C5 library : C5 UserGuideExamples - TreeTraversal
public static void BreadthFirst(Tree<T> t, Action<T> action)
{
IQueue<Tree<T>> work = new CircularQueue<Tree<T>>();
work.Enqueue(t);
while (!work.IsEmpty)
{
Tree<T> cur = work.Dequeue();
if (cur != null)
{
work.Enqueue(cur.t1);
work.Enqueue(cur.t2);
action(cur.val);
}
}
}
回答4:
Another No-recursive apporoach..
void LevelOrder(node * root)
{
queue<node *> q;
node *n=new node;
n=root;
while(n)
{
cout<<n->data<<" ";
if(n->left)
q.push(n->left);
if(n->right)
q.push(n->right);
n=q.front();
q.pop();
}
}
回答5:
void levelorder (Node *root)
{
if(!root)
return;
queue<Node*> Q;
Q.push(root);
while(!Q.empty())
{
Node *current = Q.front();//returns the front element in queue
cout <<current->data;//printing the front node of queue
if(current->left!=NULL)
Q.push(current->left);//pushing left child
if(current->right!=NULL)
Q.push(current->right);//pushing right child
Q.pop();//removing front element from queue.
}
}
来源:https://stackoverflow.com/questions/15166617/level-order-traversal-of-a-binary-tree