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;
      }
    
  • 相关阅读:
    Fragment_3_Androidx中返回键的处理
    2.2.3.Architecture components_View Binding
    2.2.2.Architecture components_data binding2_源码分析
    经典排序
    动态规划求解最长公共子序列
    全排列问题
    钢条切割
    KMP
    Queue
    Stack
  • 原文地址:https://www.cnblogs.com/xym4869/p/13819593.html
Copyright © 2011-2022 走看看