Given a node in a binary search tree, return the next bigger element, also known as the inorder successor.
For example, the inorder successor of 22 is 30.
10
/ \
5 30
/ \
22 35
You can assume each node has a parent
pointer.
Example:
Input: tree = [10,5,30,null,null,22,35], key = 22
Output: 30
Approach
C++
#include <bits/stdc++.h>using namespace std;//struct for treenodestruct TreeNode{int data;TreeNode *left;TreeNode *right;TreeNode(int data){this->data = data;this->left = NULL;this->right = NULL;}};//find minimum value node in a given BSTTreeNode *findMinimum(TreeNode *root){while (root->left){root = root->left;}return root;}void inorderSuccessor(TreeNode *root, TreeNode *&succ, int key){// base caseif (root == NULL){succ = NULL;return;}if (root->data == key){if (root->right){succ = findMinimum(root->right);}}else if (key < root->data){// update successor to the current node// and reccur for left subtreesucc = root;inorderSuccessor(root->left, succ, key);}// if the given key is more than the root node,// then reccur for the right subtreeelse{inorderSuccessor(root->right, succ, key);}}int main(){TreeNode *root = new TreeNode(10);root->left = new TreeNode(5);root->right = new TreeNode(30);root->right->left = new TreeNode(22);TreeNode *succ = NULL;root->right->right = new TreeNode(35);int key = 22;inorderSuccessor(root, succ, key);cout << succ->data;return 0;}
No comments:
Post a Comment