C++ non recursive queue implementation binomial tree breadth first traversal
- 2020-04-02 03:11:07
- OfStack
This article illustrates the breadth first traversal of a binary tree for C++ non-recursive queues. Share with you for your reference. The details are as follows:
Breadth first non-recursive binary tree traversal (or hierarchical traversal) :
void widthFirstTraverse(TNode* root) {
queue<TNode*> q; //The queue
q.enqueue(root);
TNode* p;
while(q.hasElement()) {
p = q.dequeue(); //The queue leader element goes out of the queue
visit(p); //Accessing p node
if(p->left)
q.enqueue(p->left);
if(p->right)
q.enqueue(p->right);
}
}
Two related examples are included:
1. Recursively traverse the binary tree in order
void preTraverse(TNode* root) {
if(!root)
return;
visit(root);
preTraverse(root->left);
preTraverse(root->Right);
}
2. Non-recursive order traversal binary tree
void preTraverseNonRecursive(TNode* root) {
stack<TNode> stack; //The stack
stack.push(root);
TNode* p;
while(!stack.isEmpty()) { //The stack Is not empty
p = stack.pop();
visit(p);
if(p->pRight)
s.push(p->pRight);
if(p->pLeft)
s.push(p->pLeft);
}
}
Hope that the article described in the C++ programming to help you.