Non-recursive binary tree

Of the binary tree preorder, inorder, postorder traversal from the root are the beginning and during the traversal, the route through the nodes are the same, just a different order of access.
Preorder is encountered when the node depth on access, preorder is encountered when accessing nodes on the left subtree returns in depth, then preorder traversal is met when the right sub-tree root in return to visit in this process, the anti-back node order as the junction depth of the opposite, that the first in-depth and then return, which is reminiscent of the stack, and want to achieve non-recursive binary tree traversal, you need to use the stack the idea is implemented

Preorder (DLR)

Preorder recursive process is

(1) Access root node
(2) preorder left subtree of the root
(3) preorder right subtree root

The preorder traversal non-recursive procedure is

First push the root node, when the stack is not empty, and access to the stack, followed by the right and left nodes into the stack (the stack FILO, the advanced stack and right node)

Figure:

void PreOrder(Btnode *b)
{
    Btnode *p;    
    SqStack st;
    InitStack(st);
    if (b != NULL)      
    {
        Push(st, b);    //根结点入栈
        while (!StackEmpty(st))
        {
            Pop(st, p);                   //根结点出栈
            printf("%c",p->data);              //在此处用输出根接地那的值表示出栈
            if (p->right != NULL)         //当右子树非空
                Push(st, p->right);   //右孩子入栈
            if (p->left != NULL)          //当左子树非空
                Push(st, p->left);    //左孩子入栈
        }
        printf("\n");
    }
    DestroyStack(st);
}

aha, first added here, and the rest tomorrow and then continue it!

Guess you like

Origin www.cnblogs.com/kangna/p/11846156.html