welcome to my blog
LeetCode Top Interview Questions 285. Inorder Successor in BST (Java版; Medium)
题目描述
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
The successor of a node p is the node with the smallest key greater than p.val.
Example 1:
Input: root = [2,1,3], p = 1
Output: 2
Explanation: 1's in-order successor node is 2. Note that both p and the return value is of TreeNode type.
Example 2:
Input: root = [5,3,6,2,4,null,null,1], p = 6
Output: null
Explanation: There is no in-order successor of the current node, so the answer is null.
Note:
If the given node has no in-order successor in the tree, return null.
It's guaranteed that the values of the tree are unique.
第一次做; 利用BST的性质定位节点: 左子树的数都比根节点小, 右子树的数都比根节点大; 核心: 注意递归函数的思考方式, 每一个递归函数中root都是根节点, 没有父节点, 也就是仅仅思考以root为根的数
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if(root==null)
return null;
TreeNode res = null;
if(root.val > p.val){
res = inorderSuccessor(root.left, p);
return res == null ? root : res;
}
第一次做; 参考了题解, 利用BST的性质: 左子树的值都比根小, 右子树的值都比根大, 这个性质能很好地定位某个节点
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
TreeNode res = null;
while(root!=null){
if(root.val > p.val){
res = root;
root = root.left;
}
else{
root = root.right;
}
}
return res;
}
}
第一次做; 中序遍历, 递归, 左根右; 开始写错了, 把处理root的代码放到了base case中, 这样就不能保证root是大于p的节点中值最小的节点了
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if(root==null)
return null;
TreeNode leftRes = inorderSuccessor(root.left, p);
if(leftRes!=null)
return leftRes;
if(root.val>p.val)
return root;
TreeNode rightRes = inorderSuccessor(root.right, p);
return rightRes;
}
}