
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Inorder Successor in BST in C++
Suppose we have a binary search tree and a node in it, we have to search the in-order successor of that node in the BST. As we know that the successor of a node p is the node with the smallest key greater than p.val.
So, if the input is like root = [2,1,3], p = 1,
then the output will be 2,
To solve this, we will follow these steps −
Define recursive method inorderSuccessor(), this will take root and p
if root null, then −
return null
if val of root <= val of p, then −
return inorderSuccessor(right of root , p)
Otherwise
option := inorderSuccessor(left of root , p)
return (if option is zero, then root, otherwise option)
Example
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class TreeNode{ public: int val; TreeNode *left, *right; TreeNode(int data){ val = data; left = NULL; right = NULL; } }; class Solution { public: TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { if(!root) return NULL; if(root->val <= p->val){ return inorderSuccessor(root->right, p); } else{ TreeNode* option = inorderSuccessor(root->left, p); return !option ? root : option; } } }; main(){ TreeNode *root = new TreeNode(2); root->left = new TreeNode(1); root->right = new TreeNode(3); TreeNode *p = root->left; Solution ob; cout << (ob.inorderSuccessor(root, p))->val; }
Input
{2,1,3},1
Output
2
- Related Articles
- Inorder Successor in BST II in C++
- Populate Inorder Successor for all nodes in C++
- Program to find Inorder Successor of a binary search tree in C++
- Replace Each Node in Binary Tree With The Sum Of Its Inorder Predecessor And Successor Using C++
- Convert a normal BST to Balanced BST in C++
- Largest BST Subtree in C++
- Find k-th smallest element in BST (Order Statistics in BST) in C++
- Delete Node in a BST in C++
- Preorder from Inorder and Postorder traversals in C++
- Maximum Sum BST in Binary Tree in C++
- Largest BST in a Binary Tree in C++
- Preorder Successor of a Node in Binary Tree in C++
- Postorder successor of a Node in Binary Tree in C++
- Convert BST to Max Heap in C++
- Convert BST to Min Heap in C++

Advertisements