多叉树(二叉树)的递归与非递归的后序遍历

之前说过前序遍历
这次我就教教大家如何用前序遍历的方法搞定后序遍历

之前写过的结构体不再重复书写了

void dfs( TreeNode *root ){
    if( root == NULL )
        return ;
    dfs( root->left );
    dfs(root->right );
        cout << root->val<<endl ;
}

观察下后续遍历恰好是前序遍历的反向,那么我们有没有什么方便的方法解决吗

有我们利用两个栈
二叉树的

vector<int> postorderTraversal(TreeNode* root) {
       vector<int> ans ;
       if( root == NULL )
          return ans ;
       stack< TreeNode * > slist;
       stack< int > res ;
       slist.push(root);

       while( slist.size() ){
           TreeNode *top = slist.top();
           slist.pop();
           res.push(top->val);
           if( top ->left)
               slist.push(top->left);
           if( top->right )
               slist.push(top->right);
       }
       while( res.size() ){
           ans.push_back( res.top()) ;
           res.pop();
       }
       return ans ; 
   }

为什么这么做观察

当前序遍历更改左右子树顺序

void dfs( TreeNode *root){
    if( root == NULL ) 
        return NULL ;
    cout << root->val <<endl;
    dfs( root->right );
    dfs( root->left);
}

那么代码恰好是上面不使用第二个辅助栈的解法

那么反转后的答案就是我们后序遍历的答案

多叉树参考之前利用树的思路与这里用辅助栈前序代替后序


vector<int> postorder(Node* root) {
      vector<int> ans ;
       if( root == NULL )
           return ans ; 
       stack< Node *> slist ;
       stack<int> res;
       slist.push(root );
       while( slist.size() ){
           Node * top = slist.top();
           slist.pop();
           res.push(top->val);
           for( int i=0 ; i<top->children.size() ; i++){
               slist.push( top->children[i] ) ;
           }
       }
       while( res.size() ){
           ans.push_back( res.top()) ;
           res.pop();
       }
       return ans ; 
   }

猜你喜欢

转载自blog.csdn.net/weixin_38739799/article/details/79166710