二叉树的递归和非递归方式的三种遍历

二叉树的递归方式遍历

前序遍历

void preOrderRecur(Tree* tree)
{
    if(tree==NULL) return ;
    cout<<tree->data<<" ";
    preOrderRecur(tree->lson);
    preOrderRecur(tree->rson);
}

中序遍历

void inOrderRecur(Tree* tree)
{
    if(tree==NULL) return ;
    inOrderRecur(tree->lson);
    cout<<tree->data<<" ";
    inOrderRecur(tree->rson);
}

后序遍历

void posOrderRecur(Tree* tree)
{
    if(tree==NULL) return ;
    posOrderRecur(tree->lson);
    posOrderRecur(tree->rson);
    cout<<tree->data<<" ";
}

非递归形式的二叉树的三种遍历方式

前序遍历

void PreOrderRecur(Tree* tree)
{    
    stack<TreeNode*> sta;
    while(!sta.empty()) sta.pop();
    sta.push(tree);
    while(!sta.empty()) {
        Tree* cur  = sta.top();
        sta.pop();
        cout<<cur->data<<" ";
        if(cur->rson!=NULL) sta.push(cur->rson);
        if(cur->lson!=NULL) sta.push(cur->lson);
    }
}

中序遍历

void InOrderRecur(Tree* tree)
{    
    stack<TreeNode*> sta;
    while(!sta.empty()) sta.pop();
    while(!sta.empty() || tree!=NULL) {
        if(tree==NULL)  {
            Tree* cur = sta.top();
            sta.pop();
            cout<<cur->data<<" ";
            tree=cur->rson;
        } else {
            sta.push(tree);
            tree=tree->lson;
        }
    }
}

后序遍历

一个栈的实现
vector<int> postorderTraversal(TreeNode *root) {
        // write your code here
        vector<int> order;
        if(root == NULL)
            return order;

        stack<TreeNode*> s;
        TreeNode *cur;         //当前结点 
        TreeNode *pre=NULL;    //前一次访问的结点 
        s.push(root);

        while(!s.empty()) {
            cur=s.top();
            //如果当前结点没有孩子结点或者孩子节点都已被访问过 
            if((cur->left==NULL&&cur->right==NULL)|| (pre!=NULL&&(pre==cur->left||pre==cur->right))) {
                order.push_back(cur->val);
                s.pop();
                pre=cur; 
            }
            else {
                if(cur->right!=NULL)
                    s.push(cur->right);
                if(cur->left!=NULL)    
                    s.push(cur->left);
            }
        }
        return order;
    }
两个栈的方法实现
void PosOrderRecur(Tree* tree)
{
    stack<TreeNode*> sta;
    stack<TreeNode*> Sta;
    while(!sta.empty()) sta.pop();
    while(!Sta.empty()) Sta.pop();
    sta.push(tree);
    while(!sta.empty()) {
        Tree* cur = sta.top();
        sta.pop();Sta.push(cur);
        if(cur->lson!=NULL) sta.push(cur->lson);
        if(cur->rson!=NULL) sta.push(cur->rson);
    }
    while(!Sta.empty()) {
        cout<<Sta.top()->data<<" ";
        Sta.pop();
    }
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值