[leetcode]Inorder Successor in BST

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);
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值