LeetCode 173. Binary Search Tree Iterator (binary search)

topic

Meaning of the questions: implement a BST's Next () function, the output BST in the small to large numbers.

Solution: topic that Next () time-efficient O (1), space efficiency O (h), h is the height of the tree. We maintain a stack, the results preorder traversal of the deposit into the left subtree.

Next remove the top element each time, and then traverse the preamble of the top element of the right subtree traverse left subtree portion.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
public:
    vector<TreeNode*> stack;
    BSTIterator(TreeNode* root) {
        
        if(root!=NULL)
            DFS(root);
        
    }
    
    /** @return the next smallest number */
    int next() {
        
        TreeNode* term = stack[stack.size()-1];
        
        stack.pop_back();
        
        if(term->right!=NULL)
        {
            DFS(term->right);
        }
        
        return term->val;
        
    }
    
    /** @return whether we have a next smallest number */
    bool hasNext() {
        
        if(stack.size()!=0)
            return true;
        else
            return false;
        
    }
    
    void DFS(TreeNode* term)
    {
        
        stack.push_back(term);
        if(term->left!=NULL)
            DFS(term->left);
    }
};

/**
 * Your BSTIterator object will be instantiated and called as such:
 * BSTIterator* obj = new BSTIterator(root);
 * int param_1 = obj->next();
 * bool param_2 = obj->hasNext();
 */

Guess you like

Origin www.cnblogs.com/dacc123/p/12236133.html