zoukankan      html  css  js  c++  java
  • LeetCode——二叉搜索树中的顺序后继

    Q:给你一个二叉搜索树和其中的某一个结点,请你找出该结点在树中顺序后继的节点。
    结点 p 的后继是值比 p.val 大的结点中键值最小的结点。

    示例 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:

    • 如果当前节点有右孩子,找到右孩子,再持续往左走直到节点左孩子为空,直接返回该节点。
    • 如果没有的话,就需要用到非递归的中序遍历。维持一个栈,当栈中有节点时:
      • 往左走直到节点的左孩子为空,并将每个访问过的节点压入栈中。
      • 弹出栈中节点,判断当前的前继节点是否为 p,如果是则直接返回当前节点。如果不是,将当前节点赋值给前继节点。
      • 往右走一步。
    • 如果走到这一步,说明不存在顺序后继,返回空。
      public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        if (p.right != null) {
          p = p.right;
          while (p.left != null) p = p.left;
          return p;
        }
    
        Stack<TreeNode> stack = new Stack<>();
        int inorder = Integer.MIN_VALUE;
    
        while (!stack.isEmpty() || root != null) {
          while (root != null) {
            stack.push(root);
            root = root.left;
          }
    
          root = stack.pop();
          if (inorder == p.val) return root;
          inorder = root.val;
    
          root = root.right;
        }
    
        return null;
      }
    

    类似查找前驱:
    如果当前节点的左子树不为空,那么该点的前驱节点为该点左子树中最右的节点
    如果当前节点的左子树为空,那么该点的前驱节点为从该点往上延伸,如果延伸到的点为其父亲节点的右孩子,那么这个父亲节点就是该点的前驱节点

      public TreeNode inorderPrecursor(TreeNode root, TreeNode p) {
        if (p.left!= null) {
          p = p.left;
          while (p.right!= null) p = p.right;
          return p;
        }
    
        Stack<TreeNode> stack = new Stack<>();
        int inorder = Integer.MIN_VALUE;
    
        while (!stack.isEmpty() || root != null) {
          while (root != null) {
            stack.push(root);
            root = root.left;
          }
    
          root = stack.pop();
          if (root== p.val) return inorder;
          inorder = root.val;
    
          root = root.right;
        }
    
        return null;
      }
    
  • 相关阅读:
    作业二 Git的安装与使用
    第一次作业
    字符串、文件操作,英文词频统计预处理
    了解大数据的特点、来源与数据呈现方式以及用Python写Mad Libs游戏
    第五次作业:结对项目-四则运算 “软件”之升级版
    第四次作业:个人项目-小学四则运算 “软件”之初版
    第3次作业:阅读《构建之法》1-5章
    分布式版本控制系统Git的安装与使用
    第一次作业-准备
    字符串操作,英文词频统计预处理
  • 原文地址:https://www.cnblogs.com/xym4869/p/13792636.html
Copyright © 2011-2022 走看看