binary-tree-postorder-traversal(二叉树后序遍历)

版权声明:版权归作者所有,转发请标明 https://blog.csdn.net/weixin_40087851/article/details/81947783

题目描述

  • Given a binary tree, return the postorder traversal of its nodes’ values.
  • For example:Given binary tree{1,#,2,3},return[3,2,1].
  • Note: Recursive solution is trivial, could you do it iteratively?
  • 翻译:给定二叉树,返回二叉树后序遍历的结果(非递归版本)

分析

  • 二叉树后序遍历是:左->右->中。采用这个次序进行递归求解十分容易,我们直接上代码:
    void recursion(TreeNode *root,vector<int>& res){
        if(root==nullptr)
            return;
        recursion(root->left,res);
        recursion(root->right,res);
        res.push_back(root->val);
    }
  • 递归的思想其实就是栈思想,因此非递归版本采用栈来实现。我们先来看看二叉树前序遍历与后序遍历的区别:

    • 前序遍历:中->左->右
    • 后序遍历:左->右->中
    • 后序遍历如何通过前序遍历求解?
      • 中->左->右的访问顺序变为中->右->左
      • 中->右->左反向观察为左->右->中
  • 通过上面分析我们可知,后序遍历可通过前序遍历求解,一方面改变访问顺序,另一方面将值存入栈中,便可进行反向观察。
    //递归的思想就是栈
    void nonRecursion(TreeNode *root,vector<int>& res){
        stack<TreeNode*> q;
        stack<int> s;
        q.push(root);
        while(q.size()!=0){
            TreeNode *temp=q.top();
            q.pop();
            s.push(temp->val);
            if(temp->left!=nullptr)
                q.push(temp->left);
            if(temp->right!=nullptr)
                q.push(temp->right);
        }
        while(s.size()!=0){
            res.push_back(s.top());
            s.pop();
        }
    }

总代码

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:

    void recursion(TreeNode *root,vector<int>& res){
        if(root==nullptr)
            return;
        recursion(root->left,res);
        recursion(root->right,res);
        res.push_back(root->val);
    }
    //递归的思想就是栈
    void nonRecursion(TreeNode *root,vector<int>& res){
        stack<TreeNode*> q;
        stack<int> s;
        q.push(root);
        while(q.size()!=0){
            TreeNode *temp=q.top();
            q.pop();
            s.push(temp->val);
            if(temp->left!=nullptr)
                q.push(temp->left);
            if(temp->right!=nullptr)
                q.push(temp->right);
        }
        while(s.size()!=0){
            res.push_back(s.top());
            s.pop();
        }
    }

    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> res;
        if(root==nullptr)
            return res;
        //recursion(root,res);
        nonRecursion(root,res);
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_40087851/article/details/81947783
今日推荐