BST平衡二叉树的后继结点

public class InorderSuccessorInBST {//平衡二叉树查找后继结点
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        if (p == null) {
            return null;
        }
        if (getLastEntry(root) == p) {//根节点的最右边的节点是最后节点,是没有后继结点的。
            return null;
        }
        if (p.right != null) {//查找第一个右节点的最左边的节点。
            return getFirstEntry(p.right);
        }
        //p.right == null
        TreeNode parent = root;//只有left,right没有parent节点。
        TreeNode temp = root;
        while (parent != null) {
            if (parent == p) {
                break;
            } else if (p.val < parent.val) {//左边走的时候,twmp指向父节点,parent指向子节点。挨着走。
                temp = parent;
                parent = parent.left;
            } else {//右边走的时候,temp不变,
                parent = parent.right;
            }
        }
        return temp;
    }

    private TreeNode getLastEntry(TreeNode p) {
        while (p.right != null) {
            p = p.right;
        }
        return p;
    }

    private TreeNode getFirstEntry(TreeNode p) {
        while (p.left != null) {
            p = p.left;
        }
        return p;
    }
}

猜你喜欢

转载自www.cnblogs.com/yaowen/p/11118872.html