Inorder successor in BST

1) Use inorder traversal (non-recursion);

2) Please remember inorder non-recursion traversal;

code


/**
 * 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(root == NULL || p == NULL)
        {
            return NULL;
        }

        vector<TreeNode*> stack;
        TreeNode *t = root;
        bool bNext = false;

        while(t != NULL || !stack.empty())
        {
            while(t != NULL)
            {
                stack.push_back(t);
                t = t->left;
            }

            t = stack.back();
            stack.pop_back();

            if(bNext)
            {
                return t;
            }

            if(t == p)
            {
                bNext = true;
            }

            t = t->right;
        }

        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(root == NULL || p == NULL)
        {
            return NULL;
        }

        vector<TreeNode*> stack;
        bool bNext = false;
        TreeNode* prev = NULL;

        while(root != NULL || !stack.empty())
        {
            while(root != NULL)
            {
                stack.push_back(root);
                root = root->left;
            }

            root = stack.back();
            stack.pop_back();

            if(prev == p)
            {
                return root;
            }

            prev = root;
            root = root->right;
        }

        return NULL;
    }
};

results matching ""

    No results matching ""