您的位置:首页 > 其它

285. Inorder Successor in BST

2017-08-09 00:00 134 查看
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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: