zoukankan      html  css  js  c++  java
  • 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;
      }
    
  • 相关阅读:
    php 高精度计算函数
    CSS 文本溢出显示省略号样式
    Vue import、export及export default示例详解,附带如何实现全局调用
    利用高德API获取最新的省市区数据
    TP5 基类验证器
    php 两种递归方法
    新建PO類型ZFA的固定資產時灰掉 GR Non-Valuated
    MRP 參數設置
    info record
    kill procedure in os level
  • 原文地址:https://www.cnblogs.com/xym4869/p/13819593.html
Copyright © 2011-2022 走看看