您的位置:首页 > 其它

Inorder Successor in Binary Search Tree

2016-12-13 14:45 344 查看
Given a binary search tree (See Definition) and a node in it, find
the in-order successor of that node in the BST.

If the given node has no in-order successor in the tree, return 
null
.


 Notice


It's guaranteed p is one node in the given tree. (You can directly compare the memory address to find p)
/**
* 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 root;
}
TreeNode successor = null;
while(root != null && root.val != p.val) {
if(root.val > p.val) {
successor = root;
root = root.left;
} else {
root = root.right;
}
}
//p is found
//p doesn't have right subtree
if(root.right == null) {
return successor;
}
//get the most left child of the right subtree
root = root.right;
while(root.left != null) {
root = root.left;
}
return root;
}
}

Notice that this is BST. So the successor node will be at two possible position:
its last parent node that is larger then itself;
the leftmost child of its right subtree
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  BST