• 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;
      }
    
  • 相关阅读:
    前端 day 05 5.15 JavaScript入门
    前端 day 04 5.14 CSS定位,浮动,JavaScript
    Luogu P1860 新魔法药水
    XJOI 夏令营501-511NOIP训练18 高二学堂
    Luogu P3959 宝藏
    Luogu P2184 贪婪大陆
    XJOI 夏令营501-511NOIP训练18 高三楼
    XJOI 夏令营501-511NOIP训练17 蛇形数阵
    BZOJ 3813 奇数国
    POJ 2728 Desert King
  • 原文地址:https://www.cnblogs.com/xym4869/p/13819593.html
Copyright © 2020-2023  润新知