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.
Hide Tags Tree
Hide Similar Problems (M) Binary Tree Inorder Traversal (M) Binary Search Tree Iterator
当然可以利用extra memory in order traverse整个bst再找node之后的那个值。 但其实我们可以O(n) w/o extra memory.
/**
* 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) {
if (root == NULL || p == NULL) return NULL;
TreeNode *suc = NULL;
while (root != NULL) {
if (root->val <= p->val) {
root = root->right;
} else {
suc = root;
root = root->left;
}
}
return suc;
}
};