LeetCode 285. Inorder Successor in BST

找中序遍历的后一个节点,那就中序遍历到当前节点后再往后一个,可以用递归,也可以非递归,完全没有用到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;
    }
};

猜你喜欢

转载自www.cnblogs.com/hankunyan/p/9568962.html