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;
    }
}

 

相关文章:

  • 2021-08-08
  • 2022-12-23
  • 2022-01-04
  • 2022-01-23
  • 2022-12-23
  • 2021-12-21
  • 2021-12-10
猜你喜欢
  • 2021-07-04
  • 2021-07-09
  • 2021-09-13
  • 2021-10-23
  • 2021-06-16
  • 2022-12-23
  • 2021-07-30
相关资源
相似解决方案