Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
Note: If the given node has no in-order successor in the tree, return
null
.
Solution:
Use stack to do in-order traversal.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for a binary tree node. | |
* struct TreeNode { | |
* int val; | |
* TreeNode *left; | |
* TreeNode *right; | |
* TreeNode(int x) : val(x), left(NULL), right(NULL) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { | |
stack<TreeNode*> myStack; | |
TreeNode* cur; | |
myStack.push(root); | |
cur = root->left; | |
bool metP=false; | |
while(cur!=NULL||!myStack.empty()){ | |
if(cur==NULL){ | |
TreeNode* node = myStack.top(); | |
myStack.pop(); | |
if(metP==true) | |
return node; | |
if(node == p) | |
metP=true; | |
cur = node->right; | |
continue; | |
} | |
myStack.push(cur); | |
cur=cur->left; | |
} | |
return NULL; | |
} | |
}; |
Round 2 solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for a binary tree node. | |
* struct TreeNode { | |
* int val; | |
* TreeNode *left; | |
* TreeNode *right; | |
* TreeNode(int x) : val(x), left(NULL), right(NULL) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
TreeNode* InOrder(TreeNode* root, TreeNode* p, TreeNode*& lastAccessed){ | |
if(root==NULL) | |
return NULL; | |
TreeNode* l = InOrder(root->left, p, lastAccessed); | |
if(lastAccessed==p){ | |
lastAccessed=root; | |
return root; | |
} | |
lastAccessed=root; | |
TreeNode* r = InOrder(root->right, p, lastAccessed); | |
return l!=NULL? l:r!=NULL? r:NULL; | |
} | |
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { | |
TreeNode* res=NULL; | |
if(root==NULL||p==NULL) | |
return NULL; | |
TreeNode* lastAccessed=NULL; | |
res = InOrder(root, p, lastAccessed); | |
return res; | |
} | |
}; |
No comments:
Post a Comment