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
.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if(root == null){
return null;
}
if(p.right != null){ //右边不为空直接返回右边的最左个节点
p = p.right;
while(p.left != null){
p = p.left;
}
return p;
}else{
TreeNode parent = null;
while(root != p){
if(root.val > p.val){
parent = root;//只有向左边走的时候才记录
root = root.left;
}else{
root = root.right;
}
}
return parent;
}
}
}