Problem
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
用中序遍历的方式遍历树,这里这个节点的位置有几种可能性:
- 节点有右孩子:那么找到右孩子的最左边的子孙。如果没有子孙,那么就是右孩子本身。
- 节点没有右孩子:那么找到最close的上层父亲,并且这个节点是这个父亲左子树的一员。
如果无法满足上述情况,那么就没有successor。另外,这里有几个corner case,比如p == root,并且root没有右孩子。比如,节点在node的右子树中,如果node != root,返回p,如果node == root,返回null。
/**
* 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 *find(TreeNode *root, TreeNode *p, TreeNode *treeRoot) {
if (root == NULL) {
return NULL;
}
TreeNode *left = find(root->left, p, treeRoot);
if (left != p && left != NULL) {
return left;
} else if (p == left) {
return root;
}
if (p == root) {
TreeNode *node = p->right;
TreeNode *preNode = NULL;
while (node) {
preNode = node;
node = node->left;
}
if (preNode) {
return preNode;
} else {
return root == treeRoot ? NULL : p;
}
}
TreeNode *right = find(root->right, p, treeRoot);
if (right != p && right != NULL) {
return right;
} else if (right == p) {
if (root == treeRoot) {
return NULL;
} else {
return p;
}
}
return NULL;
}
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
return find(root, p, root);
}
};