原题链接在这里: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.

最新文章

  1. window.print() 打印页面部分内容的方法
  2. Excel导入导出(篇二)
  3. MySql_设置编码
  4. ActiveReports 报表应用教程 (3)---图表报表
  5. openssl_final学习总结
  6. C#:文件、文件夹特别操作
  7. spring_150805_datasource
  8. 我给自己的Sass+Compass,在Windows下写个bat,快速cd到我的sass目录
  9. [RxJS] Displaying Initial Data with StartWith
  10. hdu 1240 Asteroids! (三维bfs)
  11. 【单调队列】【3-21个人赛】【problmeB】
  12. kobject_create_and_add
  13. Android Studio发布项目到jcenter,一行代码引入Module
  14. DirectShow使用说明
  15. 2019-1-17 前言 C#高级编程(第11版)
  16. 第十五周翻译-《Pro SQL Server Internals, 2nd edition》
  17. Java Exception 和Error
  18. 阻塞队列(BlockingQueue)
  19. Django Form&amp;ModelForm
  20. 压缩tar: Removing leading `/’ from member names

热门文章

  1. Servlet 编程 http请求类型
  2. LeetCode | Regular Expression Matching
  3. NBOJv2 1004 蛤玮打扫教室(线段树区间更新区间最值查询)
  4. velocity学习记录
  5. switch parser.p4源码
  6. [SHELL实例] (转)最牛B的 Linux Shell 命令 (一)
  7. [转]理解OAuth 2.0
  8. LR脚本技巧
  9. 时间函数 date strtotime
  10. Raft