题目来源
题目描述
给定一棵二叉搜索树和其中的一个节点 node ,找到该节点在树中的中序后继。
如果节点没有中序后继,请返回 null 。
一个结点 node 的中序后继是键值比 node.val大所有的结点中键值最小的那个。
你可以直接访问结点,但无法直接访问树。
每个节点都会有其父节点的引用。节点定义如下:
class Node {
public int val;
public Node left;
public Node right;
public Node parent;
}
进阶:
你能否在不访问任何结点的值的情况下解决问题?
class Node {
public:
int val;
Node* left;
Node* right;
Node* parent;
};
class Solution {
public:
/*
* @param root: The root of the BST.
* @param p: You need find the successor node of p.
* @return: Successor of p.
*/
Node* inorderSuccessor(Node* node) {
// write your code here
}
};
题目思路
class Solution {
public:
/*
* @param root: The root of the BST.
* @param p: You need find the successor node of p.
* @return: Successor of p.
*/
Node* inorderSuccessor(Node* node) {
if(node == nullptr){
return nullptr;
}
if(node->right == nullptr){
Node *curr = node->parent;
while (curr != nullptr && curr->val < node->val){
curr = curr->parent;
}
return curr;
}else{
Node *curr = node->right;
while (curr != nullptr && curr->left != nullptr){
curr = curr->left;
}
return curr;
}
}
};
follow up
因为不能比较值,所以下面的找不出来。
怎么找呢?可以根据node相对于parent的相对位置来判断
class Solution {
public:
/*
* @param root: The root of the BST.
* @param p: You need find the successor node of p.
* @return: Successor of p.
*/
Node* inorderSuccessor(Node* node) {
if(node == nullptr){
return nullptr;
}
if(node->right == nullptr){
Node *curr = node->parent, *child = node;
while (curr != nullptr && curr->left != child){
child = curr;
curr = curr->parent;
}
return curr;
}else{
Node *curr = node->right;
while (curr != nullptr && curr->left != nullptr){
curr = curr->left;
}
return curr;
}
}
};