LeetCode Inorder Successor in BST
2024-08-25 08:19:27
原题链接在这里:https://leetcode.com/problems/inorder-successor-in-bst/
题目:
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
Note: If the given node has no in-order successor in the tree, return null
.
题解:
successor could be自己的parent, or 右子树中最左的点.
For both cases, if p.val < root.val, update successor as root. Otherwise, root needs to be bigger, root = root.right.
Time Complexity: O(h).
Space: O(1).
AC Java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if(root == null || p == null){
return null;
}
TreeNode successor = null;
while(root != null){
if(p.val < root.val){
successor = root;
root = root.left;
}else{
root = root.right;
}
}
return successor;
}
}
跟上Inorder Successor in BST II.
最新文章
- window.print() 打印页面部分内容的方法
- Excel导入导出(篇二)
- MySql_设置编码
- ActiveReports 报表应用教程 (3)---图表报表
- openssl_final学习总结
- C#:文件、文件夹特别操作
- spring_150805_datasource
- 我给自己的Sass+Compass,在Windows下写个bat,快速cd到我的sass目录
- [RxJS] Displaying Initial Data with StartWith
- hdu 1240 Asteroids! (三维bfs)
- 【单调队列】【3-21个人赛】【problmeB】
- kobject_create_and_add
- Android Studio发布项目到jcenter,一行代码引入Module
- DirectShow使用说明
- 2019-1-17 前言 C#高级编程(第11版)
- 第十五周翻译-《Pro SQL Server Internals, 2nd edition》
- Java Exception 和Error
- 阻塞队列(BlockingQueue)
- Django Form&;ModelForm
- 压缩tar: Removing leading `/’ from member names