Morris O(n)time O(1) space


  • 0
    X
    vector<int> preorderTraversal(TreeNode* root) {
            vector<int> res;
            if (!root) return res;
            TreeNode *cur1 = root;
            TreeNode *cur2 = nullptr;
            while (cur1) {
                cur2 = cur1->left;
                if (cur2) {
                    while (cur2->right && cur2->right != cur1) {
                        cur2 = cur2->right;
                    }
                    if (!cur2->right) {
                        cur2->right = cur1;
                        res.push_back(cur1->val);
                        cur1 = cur1->left;
                        continue;
                    }
                    else {
                        cur2->right = nullptr;
                    }
                }
                else {
                    res.push_back(cur1->val);
                }
                cur1 = cur1->right;
            }
            return res;
        }
    

Log in to reply
 

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