树的前、中、后序遍历算法(递归与非递归)、层序遍历

二叉树层次遍历 非递归

void  LevelOrder(Tree* T)
{
    if(T == nullptr)
       return ;
    queue<Tree *> myqueue;
    myqueue.push(T);
    while(!myqueue.empty())
    {
        Tree *tmp = myqueue.front();
        if(tmp->leftChild != nullptr)
            myqueue.push(tmp->leftChild);
        if(tmp->rightChild != nullptr)
            myqueue.push(tmp->rightChild);
        cout << tmp.val<<" ";
        myqueue.pop();
    }

}

二叉树前序遍历 递归 与非递归

//递归
void  PreOrder(Tree* T)
{
    if(T == nullptr)
       return ;
    cout << T.val << " ";
    PreOrder(T->leftChild);
    PreOrder(T->rightChild);
}


//非递归
void preOrderF(Tree * root)
{
    if(root == nullptr)
        return ;
    stack<Tree *>s;
    s.push(root);
    Tree *p = nullptr;
    while(!s.empty())
    {
        p = s.top();
        s.pop();
        cout << p->data << " ";
        if( p->right)
            s.push(p->right);
        if(p->left)
            s.push(p->left);
    }
}

二叉树中序遍历 递归与非递归

//递归
void  InOrder(Tree *T)
{
    if(T == nullptr)
       return ;
    InOrder(T->leftChild);
    cout << T.val << " ";
    InOrder(T->rightChild);
}

//非递归
void InOrderT(Tree *root){
    if(root == nullptr)
        return ;
    stack<Tree *>s;
    Tree *p = root;
    while(p != nullptr || !s.empty())
    {
        if(p != nullptr)
        {
            s.push(p);
            p = p->left;
        }
        else{
            p = s.top();
            s.pop();
            cout << p->data << " ";
            p = p->right;
        }
    }
}

二叉树后序遍历 递归与非递归

//递归
void  PostOrder(Tree* T)
{
    if(T == nullptr)
       return ;
    PostOrder(T->leftChild);
    PostOrder(T->rightChild);
    cout << T.val << " ";
}

//非递归
void PostOrderT(Tree *root){
    if(root == nullptr)
        return ;
    stack<Tree *> s;
    vector<int> rs;
    s.push(root);
    Tree *p =nullptr;
    while(!s.empty())
    {
        p = s.top();
        s.pop();;
        rs.insert(rs.begin(),p->data);
        if(p->left)
            s.push(p->left);
        if(p->right)
            s.push(p->right);
    }

    for(int i = 0; i < rs.size(); i++)
        cout << rs[i] << " ";
}

猜你喜欢

转载自blog.csdn.net/feixi7358/article/details/82898866