엔지니어 게시판
LeetCode 솔루션 분류

173. Binary Search Tree Iterator

컨텐츠 정보

본문

[ Medium ] 173. Binary Search Tree Iterator


Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):

  • BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.
  • boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.
  • int next() Moves the pointer to the right, then returns the number at the pointer.

Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.

You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.

 

Example 1:

Input
["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
Output
[null, 3, 7, true, 9, true, 15, true, 20, false]

Explanation
BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);
bSTIterator.next();    // return 3
bSTIterator.next();    // return 7
bSTIterator.hasNext(); // return True
bSTIterator.next();    // return 9
bSTIterator.hasNext(); // return True
bSTIterator.next();    // return 15
bSTIterator.hasNext(); // return True
bSTIterator.next();    // return 20
bSTIterator.hasNext(); // return False

 

Constraints:

  • The number of nodes in the tree is in the range [1, 105].
  • 0 <= Node.val <= 106
  • At most 105 calls will be made to hasNext, and next.

 

Follow up:

  • Could you implement next() and hasNext() to run in average O(1) time and use O(h) memory, where h is the height of the tree?

관련자료

댓글 3

mingki님의 댓글

  • 익명
  • 작성일
C++
Runtime: 48 ms, faster than 27.69% of C++ online submissions for Binary Search Tree Iterator.
Memory Usage: 24.3 MB, less than 10.53% of C++ online submissions for Binary Search Tree Iterator.
class BSTIterator {
    vector<int> arr;
    int idx;
    
    void buildArr(TreeNode* root) {
        if (root) {
            buildArr(root->left);
            arr.push_back(root->val);
            buildArr(root->right);
        }
    }
    
public:
    BSTIterator(TreeNode* root) {
        buildArr(root);
        idx = 0;
    }
    
    int next() {
        return arr[idx++];
    }
    
    bool hasNext() {
        return idx < arr.size();
    }
};

9dea0936님의 댓글

  • 익명
  • 작성일
class BSTIterator:
    def __init__(self, root: Optional[TreeNode]):
        head = root
        def dfs(head):
            return dfs(head.left) + [head.val] + dfs(head.right) if head else []
        self.ans = dfs(root)
        self.iter = 0
        self.lenLst = len(self.ans)
        print(self.ans)
        
    def next(self) -> int:
        if self.iter < self.lenLst:
            temp = self.ans[self.iter]
            self.iter += 1
            return temp
            
    def hasNext(self) -> bool:
        if self.iter < self.lenLst:
            return True
        else:
            return False
        

bobkim님의 댓글

  • 익명
  • 작성일
Runtime: 31 ms, faster than 76.77% of C++ online submissions for Binary Search Tree Iterator.
Memory Usage: 25.5 MB, less than 6.08% of C++ online submissions for Binary Search Tree Iterator.
class BSTIterator {
private :
    int n=0;
    std::vector<TreeNode*> TreeNodeVec;
public:
    BSTIterator(TreeNode* root) {
        Treesort(root);
    }
    
    void Treesort(TreeNode* p){
            if(p == nullptr){
            return;
        }
        if(p->left != nullptr)
            Treesort(p->left);
        
        TreeNodeVec.push_back(p);
        
        if(p->right != nullptr)
            Treesort(p->right);
    }
    
    
    int next() {
        n++;
        return TreeNodeVec[n-1]->val;
    }
    
    bool hasNext() {
        return TreeNodeVec.size() >= n+1;  
    }
};
전체 396 / 4 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 222 명
  • 오늘 방문자 3,253 명
  • 어제 방문자 5,793 명
  • 최대 방문자 11,134 명
  • 전체 회원수 1,106 명
알림 0