Using the stack structure, first push the root node into the stack, then save the root node, let the root node pop out of the stack, and then judge whether the root node has a left subtree and a right subtree, and push it into the stack if there is. Loop in turn, when the stack is empty, the traversal ends.
Don't forget to destroy the stack
void PreOrderNor(PBTNode pRoot)
{
PBTNode pCur =NULL;
Stack s;
StackInit(&s);
if (NULL== pRoot)
return;
StackPush(&s, pRoot);
while (!StackEmpty(&s))
{
pCur = StackTop(&s);
StackPop(&s);
printf("%c", pCur->_data);
if (pCur->pRight)
StackPush(&s, pCur->pRight);
if (pCur->pLeft)
StackPush(&s, pCur->pLeft);
}
StackDestory(&s);
}
2. In-order traversal
recursion
Returns empty if the binary tree is empty
Traverse the left subtree, the root node, and the right subtree in turn
Access the left subtree of the cyclic binary tree, if it exists, push it into the stack; if it does not exist, print the root node, pop the node from the stack, and visit the right subtree of the node
Determine whether the node has left and right subtrees, if not, print it. and pop the node
If a tree has a right subtree, save its right subtree, and judge for the second time whether the node has been visited. If it has been visited, it will not be visited.
Queue the pointer of the root node of the binary tree
If the queue is not empty, dequeue the head element in the queue, then put the left child pointer (if any) of the head element into the queue, and then put the right child pointer (if any) of the head element into the queue, repeat this process process until there are no elements in the queue
void LevelOrder(PBTNode pRoot)
{
Queue q;
PBTNode pCur =NULL;
if (NULL== pRoot)
return;
QueueInit(&q);
QueuePush(&q, pRoot);
while (!QueueEmpty(&q))
{
pCur = QueueFrontData(&q);
QueuePop(&q);
printf("%c", pCur->_data);
if (pCur->pLeft)
QueuePush(&q, pCur->pLeft);
if (pCur->pRight)
QueuePush(&q, pCur->pRight);
}
QueueDestory(&q);
}