Postorder traversal of binary tree (stack implementation)

Title: https://leetcode-cn.com/problems/binary-tree-postorder-traversal/

/**
 * 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 == nullptr) return res;
        stack<TreeNode*> st;
        st.push(root);
        while(!st.empty()) {
            TreeNode *cur = st.top();
            st.pop();
            if(cur->left == nullptr && cur->right == nullptr) {
                res.push_back(cur->val);
            }else {
                TreeNode *l = cur->left;
                TreeNode *r = cur->right;
                cur->left = cur->right = nullptr;
                st.push(cur);
                if(r != nullptr) st.push(r);
                if(l != nullptr) st.push(l);
            }
        }
        return res;
    }
};
Published 152 original articles · praised 2 · visits 6460

Guess you like

Origin blog.csdn.net/weixin_43918473/article/details/104632344