您的位置:首页 > 产品设计 > UI/UE

[leetcode]Inorder Successor in BST

2015-12-31 14:29 477 查看

Problem

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
.



Solution 1.  Iterative 利用BST的排序特性

找target节点的successor, 就是找比它大的最小的那个节点。

利用BST的特性:用runner从根开始遍历节点

 1) 如果runner的值比target节点小或者相等,排除左边往右边找,因为该节点左边的都比该节点小。

2) 如果一个节点比target节点大,那它就有可能是要找的successor, 暂且标记为successor. 

重复上面两步,直到runner为空

Time O(N),  Space O(1)

class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* target) {
if(!root || !target) return NULL;

TreeNode* runner = root, *suc = NULL;
while(runner){
if(runner->val > target->val){
suc = runner;
runner = runner->left;
}
else {
runner = runner->right;
}
}
return suc;
}
};


Solution 2.  Recursive  同样利用BST的排序特性

class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* target) {
if(!root) return NULL;
if(root->val <= target->val){
return inorderSuccessor(root->right, target);
}
else{
TreeNode* rst = inorderSuccessor(root->left, target);
return rst ? rst : root;
}
}
};


Solution 3. 利用 inorder traversal 的特性

我的思路是 : 从根节点开始向下遍历,如果找到目标节点,那么向上返回一层的那个root节点就是答案。However,写出来的code不work。

有哪位大神看到了帮忙指导一下啊。。
class Solution {
TreeNode* helper(TreeNode* root, TreeNode* target, bool& found){
if(!root) return NULL;
if(target == root) { found = true; return NULL;}

TreeNode* left = helper( root->left, target, found);
if(found) return root;

return helper(root->right, target, found);
}
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* target) {
bool found = false;
return helper(root, target, found);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息