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;
}
}
}

--

--

--

SDE 3 at Walmart Labs

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

Recommended from Medium

Traceable Interview Experience for SDE-1 (On-campus)

Reactive Clean Architecture with Android Architecture Components

What I learned this week #2

Heap Data Structure Implementation — Swift 4

Open API Initiative and future of API Space with the Open API Specification

Apache Airflow at Devoted Health

How to build an auction website the cheapest.

Mario Torchia is the new InSilicoTrials’ Vice President of Sales & Marketing

Mario Torchia is the new InSilicoTrials’ Vice President of Sales & Marketing

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
shailja dalmia

shailja dalmia

SDE 3 at Walmart Labs

More from Medium

DIY Smart Blinds — Part 1

Performance Analysis: Virtualization Vs Containerization

CS373 Spring 2022: Brock Moore Week 9

OOP’s, What are the important concepts of OOPS in Java?