二叉树的前序、中序、后序三种遍历的六种实现方式(递归、非递归)(C++)

实现语言:C++

存储方式:链式存储

struct TreeNode{
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode(int x):val(x),left(NULL),right(NULL);
}
一、前序遍历

前序遍历方式:根左右

递归实现:递归实现的方式代码一般比较简单快捷。

void preorder1(TreeNode* root){
       if(root){
            cout<<root->val;
            preorder1(root->left);
            preorder1(root->right);
       }
       cout<<endl;
}

非递归实现:由于前序遍历方式有回溯的过程,所以需要用到栈把遍历过的节点存起来。
void preorder2(TreeNode* root){
      if(root==NULL)
           cout<<"The tree is empty!"<<endl;
      stack<TreeNode*> s;
      while(root||!s.empty()){
              while(root){
                     cout<<root->val;
                     s.push(root);
                     root=root->left;
              } 
              root=s.top();
              s.pop();
              root=root->right; 
      }
}

二、中序遍历

中序遍历的方式:左根右

递归实现:

<pre name="code" class="cpp">void midorder1(TreeNode* root){
            if(root){
                 midorder1(root->left);
                 cout<<root->val;
                 midorder1(root->right);
            }
}

 非递归实现: 

void midorder2(TreeNode* root){
        if(root)
            cout<<"empty!"<<endl;
        stack<int> s;
        while(root||!s.empty()){
                while(root){
                s.push(root);
                root=root->left; 
                }
                root=s.top();
                s.pop();
                cout<<root->val;
                root=root->right;
        }
}
三、后序遍历

后序遍历的方式:左右根

递归实现:

void postorder1(TreeNode* root){
          if(root){
               postorder(root->left);
               postorder(root->right);
               cout<<root->val;
          }
}
非递归实现:后序遍历的过程比较麻烦,有些节点需要遍历两遍(含有右子树的那些节点) 所以通过设置一个标志位来标志节点的当前遍历次数。

void postorder2(TreeNode* root){
    if(root==NULL)
        cout<<"empty!"<<endl;
    else{
        stack<TreeNode*> s;
        stack<int> v;
        while(root){
            s.push(root);
            v.push(0);
            root=root->left;
        }
        while(!s.empty()){
            root=s.top();
            while(root->right&&v.top()==0)            {
                v.pop();
                v.push(1);
                root=root->right;
                s.push(root);
                v.push(0);
                while(root->left){
                     s.push(root);
                     v.push(0);
                     root=root->left;
                }
           }
           root=s.top();
           cout<<root->val;
           s.pop();
           v.pop();
        }
    }
}
















  • 14
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值