Java經典算法:BST中的有序繼承者

給定二叉搜索樹和其中的一個節點,請在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的資料與面試題,如果你在技術上面想提升自己的話,可以關注我,私信發送領取資料或者在評論區留下自己的聯繫方式,有時間記得幫我點下轉發讓跟多的人看到哦。在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章