cpp_O(1) space, Morris Traversal


  • 0
    A

    Try to avoid using recursive solution and using morris traversal algorithm to solve most of trees' questions.

    class Solution {
    public:
        vector<int> preorderTraversal(TreeNode* root) {
            vector<int> res;
            TreeNode* t=nullptr;
            while (root) {
                if (root->left) {
                    t = root->left;
                    while (t->right && t->right!=root) t = t->right;
                    if (t->right) {
                        t->right = nullptr;
                        root = root->right;
                    } else {
                        t->right = root;
                        res.push_back(root->val);
                        root = root->left;
                    }
                } else {
                    res.push_back(root->val);
                    root = root->right;
                }
            }
            return res;
        }
    };
    

Log in to reply
 

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