The BST nodes cannot be modified? The Morris Traversal solution just encounts RuntimeError!


  • 0
    int kthSmallest(struct TreeNode* root, int k)
    {
        while(root)
        {
            if(!root->left)
            {
                k--;
                if(!k) return root->val;
                root = root->right;
            }
            else
            {
                struct TreeNode* pre = root->left;
                while(pre->right && pre->right!=root)
                    pre = pre->right;
                if(!pre->right)
                {
                    pre->right = root;
                    root = root->left;
                }
                else
                {
                    k--;
                    if(!k) return root->val;
                    pre->right = NULL;
                    root = root->right;
                }
            }
        }
    }

Log in to reply
 

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