[LeetCode] Inorder Successor in BST
2015-09-22 14:47
323 查看
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
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.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { if (p == NULL) return NULL; TreeNode *res = NULL; if (p->right != NULL) { res = p->right; while (res->left) res = res->left; return res; } TreeNode *q = root; while (q != NULL && q->val != p->val) { if (q->val > p->val) { res = q; q = q->left; } else { q = q->right; } } return res; } };
相关文章推荐
- ASP.NET MVC 3 Razor 视图引擎 基本语法
- Mybatis List列表In查询实现的注意事项
- java 和 maven 的环境变量设置
- jQuery实现的经典滑动门效果
- xtrabackup备份工具使用详解
- PHP Framework - CodeIgniter
- 导航 - 利用系统自带的App导航
- git 的使用
- ASP.NET MVC 3 Razor 视图引擎 基本语法
- App Transport Security(ATS)
- VC6下采用ShellExecuteEx提升管理员权限
- 将32位代码向64位平台移植的注意事项
- CocoaPods安装和使用教程
- Memory Controller
- Android启动过程深入解析
- linux下samba初步了解
- sublime汉化
- HTTP 错误 401.2 - Unauthorized
- .Net 开源控件 NPlot使用小结
- Sublime Text 2 支持GB2312和GBK