LeetCode——二叉搜索树中的中序后继 II
Q:给定一棵二叉搜索树和其中的一个节点 node ,找到该节点在树中的中序后继。
如果节点没有中序后继,请返回 null 。
一个结点 node 的中序后继是键值比 node.val大所有的结点中键值最小的那个。
你可以直接访问结点,但无法直接访问树。每个节点都会有其父节点的引用。节点定义如下:
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node parent;
}
示例 1:

输入: tree = [2,1,3], node = 1
输出: 2
解析: 1 的中序后继结点是 2 。注意节点和返回值都是 Node 类型的。
示例 2:

输入: tree = [5,3,6,2,4,null,null,1], node = 6
输出: null
解析: 该结点没有中序后继,因此返回 null 。
A:
- 若 node 结点有右孩子,则它的后继在树中相对较低的位置。我们向右走一次,再尽可能的向左走,返回最后所在的结点。
- 若 node 结点没有右孩子,则它的后继在树中相对较高的位置。我们向上走到直到结点 tmp 的左孩子是 node 的父节点时,则 node 的后继为 tmp。
  public Node inorderSuccessor(Node x) {
    // the successor is somewhere lower in the right subtree
    if (x.right != null) {
      x = x.right;
      while (x.left != null) x = x.left;
      return x;
    }
    // the successor is somewhere upper in the tree
    while (x.parent != null && x == x.parent.right) x = x.parent;
    return x.parent;
  }
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号