码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 285. Inorder Successor in BST

时间:2018-09-01 12:39:00      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:stack   ret   while   遍历   ==   div   sso   span   false   

找中序遍历的后一个节点,那就中序遍历到当前节点后再往后一个,可以用递归,也可以非递归,完全没有用到BST的性质。

class Solution {
public:
    TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
        stack<TreeNode *> s;
        TreeNode *cur=root;
        bool flag=false;
        while (!s.empty() || cur!=NULL){
            while (cur){
                s.push(cur);
                cur = cur->left;
            }
            cur = s.top(); s.pop();
            if (flag) return cur;
            if (cur==p) flag=true;
            
            cur = cur->right;
        }
        return NULL;
    }
};

 

也可以充分利用BST的性质,如果p比当前节点小,说明在左子树,res=root;否则去右子树搜索。

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

 

LeetCode 285. Inorder Successor in BST

标签:stack   ret   while   遍历   ==   div   sso   span   false   

原文地址:https://www.cnblogs.com/hankunyan/p/9568962.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!