【题解】二叉树的前中后遍历

文章目录

  • 二叉树的前序遍历
  • 二叉树的中序遍历
  • 二叉树的后序遍历

二叉树的前序遍历

题目链接:二叉树的前序遍历

解题思路1:递归

代码如下:

    void preorder(vector<int>& res, TreeNode* root){
        if(root == nullptr) return;//遇到空节点就返回
        res.push_back(root->val);//先遍历根节点
        preorder(res, root->left);//再遍历左子树
        preorder(res, root->right);//最后遍历右子树
    }
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> res;
        preorder(res, root);
        return res;
    }

解题思路2:辅助栈

代码如下:

    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> res;
        if(root == nullptr) return res;
        stack<TreeNode*> s;
        s.push(root);
        while(!s.empty()){
            TreeNode* cur = s.top();
            res.push_back(cur->val);
            s.pop();
            if(cur->right) s.push(cur->right);
            if(cur->left) s.push(cur->left);
        }
        return res;
    }

二叉树的中序遍历

题目链接:二叉树的中序遍历

解题思路1:递归

代码如下:

    void inorder(vector<int>& res, TreeNode* root){
        if(root == nullptr) return;
        inorder(res, root->left);
        res.push_back(root->val);
        inorder(res, root->right);
    }
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        inorder(res, root);
        return res;
    }

解题思路2:辅助栈

代码如下:

    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> s;
        while(root!=nullptr || !s.empty()){
            //每次找到最左节点
            while(root != nullptr){
                s.push(root);
                root = root->left;
            }
            //访问该节点
            TreeNode* cur = s.top();
            res.push_back(cur->val);
            s.pop();
            //进入右节点
            root = cur->right;
        }
        return res;
    }

二叉树的后序遍历

题目链接:二叉树的后序遍历

解题思路1:递归

代码如下:

    void postorder(vector<int>& res, TreeNode* root) {
        if (root == nullptr) return;
        postorder(res, root->left);
        postorder(res, root->right);
        res.push_back(root->val);
    }
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        postorder(res, root);
        return res;
    }

解题思路2:辅助栈

代码如下:

    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> s;
        TreeNode* pre = nullptr;
        while(root!=nullptr || !s.empty()){
            //找到最左边的节点
            while(root != nullptr){
                s.push(root);
                root = root->left;
            }
            TreeNode* cur = s.top();
            s.pop();
            if(cur->right==nullptr || cur->right == pre){
                res.push_back(cur->val);
                pre = cur;
            }else{
                s.push(cur);
                root = cur->right;
            }
        }
        return res;
    }

你可能感兴趣的:(题目练习,算法,数据结构)