[LeetCode] C++: Intermediate Problem-Tree 145. Post-order traversal of binary tree

145. Post-order traversal of binary tree

Medium difficulty 515

Given a binary tree, return its  post-order  traversal.

Example:

Input: [. 1, null, 2,3]   
   . 1 
    \ 
     2 
    / 
   . 3 Output: [3,2,1]

Advanced: The  recursive algorithm is very simple, can you do it through an iterative algorithm?

1. Iteration

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        if(root == nullptr){
            return res;
        }
        stack<TreeNode*> stk;
        TreeNode* prev = nullptr;
        while(root != nullptr || !stk.empty()){
            while(root != nullptr){
                stk.push(root);
                root = root->left;
            }
            root = stk.top();
            stk.pop();
            if(root->right == nullptr || root->right == prev){  //没有右节点
                res.push_back(root->val);
                prev = root;
                root = nullptr;
            } else{
                stk.push(root);
                root = root->right;
            }
        }     
        return res;
    }
};

2. Recursion

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void backTraverse(TreeNode* root, vector<int>& res){
        if(root == nullptr){
            return ;
        }
        backTraverse(root->left, res);
        backTraverse(root->right, res);
        res.push_back(root->val);
    }
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        backTraverse(root, res);
        return res;
    }
};

 

Guess you like

Origin blog.csdn.net/weixin_44566432/article/details/113689051