LeetCode145. 二叉树的后序遍历

1.递归实现:

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> ans;
        postorder(ans,root);
        return ans;
    }
    
    void postorder(vector<int> &ans,TreeNode* root){
        if(root==NULL)
            return;
        postorder(ans,root->left);
        postorder(ans,root->right);
        ans.push_back(root->val);
    }
};

2.非递归实现:

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> ans;
        postorder(ans,root);
        return ans;
    }
    
    void postorder(vector<int> &ans,TreeNode* root){
        if(root==NULL)
            return;
        stack<TreeNode *> s;
        TreeNode* cur = NULL;
        TreeNode* pre = NULL;
        s.push(root);
        while(!s.empty()){
            cur = s.top();
            if((cur->left==NULL && cur->right==NULL) || (pre!=NULL && (pre==cur->left||pre==cur->right))){
                ans.push_back(cur->val);
                s.pop();
                pre = cur;
            }
            else{
                if(cur->right!=NULL)
                    s.push(cur->right);
                if(cur->left!=NULL)
                    s.push(cur->left);
            }             
        }
    }
};

说明:只有一个节点的左右孩子都为空 或者 左右孩子都被访问过了,才访问当前节点,否则的话,先把右孩子入栈,再把左孩子入栈,因为栈是先进后出的,而后序遍历是先访问左孩子,再访问右孩子,再访问父节点。

猜你喜欢

转载自blog.csdn.net/Jaster_wisdom/article/details/81337166