跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • 网易面试题: BST 的中序前驱节点
未分類
13 3 月 2021

网易面试题: BST 的中序前驱节点

网易面试题: BST 的中序前驱节点

資深大佬 : zzzrf 2

描述

给出一棵二叉搜索树以及其中的一个节点,找到这个节点在这棵树中的中序前驱节点。 在线评测地址

样例 1

输入: root = {2,1,3}, p = 1 输出: null 

样例 2

输入: root = {2,1}, p = 2 输出: 1 

用 while 循环模拟递归

/**  * Definition of TreeNode:  * public class TreeNode {  *     public int val;  *     public TreeNode left, right;  *     public TreeNode(int val) {  *         this.val = val;  *         this.left = this.right = null;  *     }  * }  */  public class Solution {     /**      * @param root: the given BST      * @param p: the given node      * @return: the in-order successor of the given node in the BST      */     public TreeNode inorderPredecessor(TreeNode root, TreeNode p) {         // write your code here         TreeNode succ = null;         while (root != null) {             if (p.val <= root.val) {                 root = root.left;             } else {                 if(succ == null || root.val > succ.val){                     succ = root;                 }                 root = root.right;                              }         }         return succ;             } } 

更多题解参考

大佬有話說 (0)

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具