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
.
这道题让我们求二叉搜索树的某个节点的中序后继节点,那么我们根据BST的性质知道其中序遍历的结果是有序的, 是我最先用的方法是用迭代的中序遍历方法,然后用一个bool型的变量b,初始化为false,我们进行中序遍历,对于遍历到的节点,我们首先看如果此时b已经为true,说明之前遍历到了p,那么此时我们返回当前节点,如果b仍为false,我们看遍历到的节点和p是否相同,如果相同,我们此时将b赋为true,那么下一个遍历到的节点就能返回了
再来看一种更简单的方法,这种方法充分地利用到了BST的性质,我们首先看根节点值和p节点值的大小,如果根节点值大,说明p节点肯定在左子树中,那么此时我们先将res赋为root,然后root移到其左子节点,循环的条件是root存在,我们再比较此时root值和p节点值的大小,如果还是root值大,我们重复上面的操作,如果p节点值,那么我们将root移到其右子节点,这样当root为空时,res指向的就是p的后继节点
public class InorderSuccessorinBST {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
Stack<TreeNode> s = new Stack<>();
boolean find = false;
TreeNode t = root;
while (t != null || !s.isEmpty()) {
while (t != null) {
s.push(t);
t = t.left;
}
t = s.pop();
if (find) {
return t;
}
if (t == p) {
find = true;
}
t = t.right;
}
return null;
}
}
public class InorderSuccessorinBST2 {
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;
}
}