您的位置:首页 > 其它

[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
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: