欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-20 13:52:44
...

题目描述

Given a binary tree, return the postorder traversal of its nodes' values.

For example:
Given binary tree{1,#,2,3},

   1
    \
     2
    /
   3

return[3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

Solution 1(非递归实现)

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    //前序遍历是根->左->右放入栈中出栈顺序根->右->左,然后逆序reverse
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int>res;
        if(root==nullptr) return res;
        stack<TreeNode*>st;
        st.push(root);
        while(!st.empty())
        {
            TreeNode *temp=st.top();
            st.pop();
            res.push_back(temp->val);
            if(temp->left!=nullptr)
                st.push(temp->left);
            if(temp->right!=nullptr)
                st.push(temp->right);
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

Solution 2(递归实现)

class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int>res;
        if(root==nullptr) return res;
        postOrder(root,res);
        return res;
    }
private:
    void postOrder(TreeNode *rootptr,vector<int>&ret)
    {
        if(rootptr!=nullptr)
        {
            postOrder(rootptr->left,ret);
            postOrder(rootptr->right,ret);
            ret.push_back(rootptr->val);
        }
        return ;
    }
};

同样可以应用到前序遍历上