# Demystifying Various BST Problems on LeetCode

1. https://leetcode.com/problems/inorder-successor-in-bst/solution/
1. GivenNode: leftNode. O/P: root
2. GivenNode: root.O/P: rightNode
3. GivenNode:rightNode.O/P: nullptr(in c++)
`TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p){TreeNode* inorder = nullptr;    if(p->right!=nullptr){           inorder = p->right;           while(inorder->left!=nullptr){                 inorder = inorder->left;           }      }return inorder;}`
`TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p){TreeNode* inorder = nullptr;stack<TreeNode* > s;TreeNode* curr = root;Treenode* prev=nullptr;while(curr!=nullptr || !s.empty()){      while(curr!=nullptr){            s.push(curr);            curr = curr->left;     }     TreeNode* temp = s.top();     s.pop();     if(prev == p)     {inorder = temp;break;}     prev = temp;     curr = temp->right;}    return inorder;}`
`TreeNode* inorderSuccessor(TreeNode* root, TreeNode*& prev,TreeNode* p){if(!root)    return nullptr;inorderSuccessor(root->left,prev,p);if(prev == p)return root;prev = root;inorderSuccessor(root->right,prev,p);}`
`void inorderSuccessorUtil(TreeNode* root,TreeNode* &succ, TreeNode* p)    {        TreeNode* curr = root;        while(curr!=nullptr){            if(curr->val> p->val) {                succ=curr;                curr=curr->left;            }            else{                curr=curr->right;            }        }    }`

--

--

--

## More from shailja dalmia

SDE 3 at Walmart Labs

Love podcasts or audiobooks? Learn on the go with our new app.

## shailja dalmia

SDE 3 at Walmart Labs