【leetcode 145. 二叉树的后序遍历】解题报告

前往二叉树的:前序,中序,后序 遍历算法

方法一:递归

    vector<int> res;
    vector<int> postorderTraversal(TreeNode* root) {
        if (!root) return res;
        if (root->left) postorderTraversal(root->left);
        if (root->right) postorderTraversal(root->right);
        res.push_back(root->val);
        return res;
    }

方法二:非递归

    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        if (!root) return res;
        stack<TreeNode*> S;
        TreeNode* p=root, *r=nullptr;
        while (p||!S.empty())
        {
            if (p)
            {
                S.push(p);
                p=p->left;
            }
            else
            {
                p=S.top();
                if (p->right&&p->right!=r)
                    p=p->right;
                else
                {
                    S.pop();
                    res.push_back(p->val);
                    r=p;
                    p=nullptr;
                }
            }
        }
        return res;
    }

方法三:非递归

    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        if (!root) return res;
        stack<TreeNode*> S;
        TreeNode* p=root;
        S.push(p);
        while (!S.empty())
        {
            p=S.top();
            S.pop();
            if (p->left) S.push(p->left);
            if (p->right) S.push(p->right);
            res.insert(res.begin(),p->val);
        }
        return res;
    }

猜你喜欢

转载自www.cnblogs.com/brianyi/p/10799541.html