[Locked] Inorder Successor in BST
2016-02-26 12:53
387 查看
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.Example
Given tree =
[2,1]and node =
1:
2 / 1
return node
2.
Given tree =
[2,1,3]and node =
2:
2 / \ 1 3
return node
3.
Note
If the given node has no in-order successor in the tree, return
null.
Challenge
O(h), where h is the height of the BST.
分析:
一般情况下,目标节点的右子节点即为中序下一个节点;如果该目标节点无右子节点,则中序下一个节点为从根节点到搜索目标节点过程中最后一次做出左节点遍历的节点。
代码:
TreeNode *successor(TreeNode *root, TreeNode *p) { TreeNode *cur = root, *record = NULL; while(cur != p) { if(p->val < cur->val) { record = cur; cur = cur->left; } else cur = cur->right; } return cur->right ? cur->right : record; }
相关文章推荐
- 拉格朗日对偶
- XSS测试平台
- 鸟哥的Linux私房菜(服务器)- 主机基本安全之一:限制 Linux 对外连线的端口
- UVA Help is needed for Dexter 11384 (递归)
- JTable隐藏指定列
- android调用c/c++基本步骤
- 服务器监控之zabbix-agent安装篇
- Hash表
- C语言中文件打开模式(r/w/a/r+/w+/a+/rb/wb/ab/rb+/wb+/ab+)浅析
- 关于12行代码崩掉浏览器的实测
- 鸟哥的Linux私房菜(服务器)- 架站文件習題解答篇
- 设计模式(7)--责任链模式
- Android include标签 放置的顺序问题
- IOS Apps 开发(Swift)(6)——Implement a Custom Control(1)
- Extjs数据代理--内存代理
- 鸟哥的Linux私房菜(服务器)- 簡易 Cluster 架設
- 微信APP支付返回-1错误
- ubuntu下配置java环境(教女朋友系列)
- 《第五项修炼》读后感(2)
- kali linux aircrack-ng 破解wifi 使用记录