给定二叉搜索树和其中的一个节点,请在BST中找到该节点的有序后继。
// Definition for a binary tree node.public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }}
Java解决方案
该节点没有指向其父节点的指针。这与BST II中的Inorder后继者不同。
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if(root==null)
return null;
TreeNode next = null;
TreeNode c = root;
while(c!=null && c.val!=p.val){
if(c.val > p.val){
next = c;
c = c.left;
}else{
c= c.right;
}
}
if(c==null)
return null;
if(c.right==null)
return next;
c = c.right;
while(c.left!=null)
c = c.left;
return c;}
最后,开发这么多年我也总结了一套学习Java的资料与面试题,如果你在技术上面想提升自己的话,可以关注我,私信发送领取资料或者在评论区留下自己的联系方式,有时间记得帮我点下转发让跟多的人看到哦。