【To Understand!】LeetCode 145. Binary Tree Postorder Traversal

LeetCode 145. Binary Tree Postorder Traversal

Solution1:递归版答案

二叉树的后序遍历递归版是很简单的,关键是迭代版的代码既难理解又难写!
迭代版链接:https://blog.csdn.net/allenlzcoder/article/details/79837841

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        my_Postordertraversal(root, res);
        return res;
    }

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

Solution2:迭代版答案

两个栈实现

先说两个栈来实现的方法,第一个栈保存的是根节点元素,第二栈是保存输出的元素!过程如下:
1.申请一个栈,将根节点入栈
2.如果栈不为空,弹出第一个栈的栈顶元素记做temp,将第一个栈顶元素出栈,然后将temp压入第二个栈。如果temp有左孩子将左孩子加入第一个栈,如果有右孩子将右孩子加入第一个栈
3.不断的重复步骤2,直到第一个栈为空,打印第二个栈,结束程序!

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        if(!root) return res;
        stack<TreeNode* > s1, s2;
        TreeNode* cur = root;
        s1.push(cur);
        while(!s1.empty()) {
            TreeNode* temp = s1.top();
            s1.pop(); s2.push(temp);
            if(temp->left != NULL) s1.push(temp->left);
            if(temp->right != NULL) s1.push(temp->right);
        }
        while(!s2.empty()) {
            res.push_back(s2.top()->val);
            s2.pop();
        }
        return res;
    }
};

一个栈实现

参考链接:https://blog.csdn.net/woshinannan741/article/details/52825163

猜你喜欢

转载自blog.csdn.net/allenlzcoder/article/details/80722198