C++ Morris algorithm, no need to reverse node


  • 0
    T

    I saw some posts used a reverseNode() to reverse node in the tree. This is not necessary. You can just push element into your ans vector<> and then reverse the portion that you just pushed in.

        void add(TreeNode* start, TreeNode* end, vector<int>& ans) {
            int startSize = ans.size();
            while(start != end) {
                ans.push_back(start->val);
                start = start->right;
            }
            ans.push_back(start->val);
            reverse(ans.begin() + startSize, ans.end());
        }
        vector<int> postorderTraversal(TreeNode* root) {
            TreeNode dummy(0);
            dummy.left = root;
            root = &dummy;
            vector<int> ans;
            while(root) {
                if(!root->left) {
                    root = root->right;
                }
                else {
                    TreeNode* curr = root->left;
                    while(curr->right && curr->right != root) {
                        curr = curr->right;
                    }
                    if(!curr->right) {
                        curr->right = root;
                        root = root->left;
                    }
                    else {
                        add(root->left, curr, ans);
                        curr->right = nullptr;
                        root = root->right;
                    }
                }
            }
            return ans;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.