{"id":8908,"date":"2021-11-28T21:18:12","date_gmt":"2021-11-29T05:18:12","guid":{"rendered":"https:\/\/zxi.mytechroad.com\/blog\/?p=8908"},"modified":"2021-11-28T21:53:17","modified_gmt":"2021-11-29T05:53:17","slug":"leetcode-173-binary-search-tree-iterator","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/tree\/leetcode-173-binary-search-tree-iterator\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 173. Binary Search Tree Iterator"},"content":{"rendered":"\n<p>Implement the&nbsp;<code>BSTIterator<\/code>&nbsp;class that represents an iterator over the&nbsp;<strong><a href=\"https:\/\/en.wikipedia.org\/wiki\/Tree_traversal#In-order_(LNR)\" target=\"_blank\" rel=\"noreferrer noopener\">in-order traversal<\/a><\/strong>&nbsp;of a binary search tree (BST):<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>BSTIterator(TreeNode root)<\/code>&nbsp;Initializes an object of the&nbsp;<code>BSTIterator<\/code>&nbsp;class. The&nbsp;<code>root<\/code>&nbsp;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.<\/li><li><code>boolean hasNext()<\/code>&nbsp;Returns&nbsp;<code>true<\/code>&nbsp;if there exists a number in the traversal to the right of the pointer, otherwise returns&nbsp;<code>false<\/code>.<\/li><li><code>int next()<\/code>&nbsp;Moves the pointer to the right, then returns the number at the pointer.<\/li><\/ul>\n\n\n\n<p>Notice that by initializing the pointer to a non-existent smallest number, the first call to&nbsp;<code>next()<\/code>&nbsp;will return the smallest element in the BST.<\/p>\n\n\n\n<p>You may assume that&nbsp;<code>next()<\/code>&nbsp;calls will always be valid. That is, there will be at least a next number in the in-order traversal when&nbsp;<code>next()<\/code>&nbsp;is called.<\/p>\n\n\n\n<p><strong>Example 1:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/assets.leetcode.com\/uploads\/2018\/12\/25\/bst-tree.png\" alt=\"\"\/><\/figure>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input<\/strong>\n[\"BSTIterator\", \"next\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\"]\n[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]\n<strong>Output<\/strong>\n<\/pre>\n\n\n<p>[null, 3, 7, true, 9, true, 15, true, 20, false]<\/p>\n\n\n\n<p><strong>Explanation<\/strong> 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<\/p>\n\n\n\n<p><strong>Constraints:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The number of nodes in the tree is in the range&nbsp;<code>[1, 10<sup>5<\/sup>]<\/code>.<\/li><li><code>0 &lt;= Node.val &lt;= 10<sup>6<\/sup><\/code><\/li><li>At most&nbsp;<code>10<sup>5<\/sup><\/code>&nbsp;calls will be made to&nbsp;<code>hasNext<\/code>, and&nbsp;<code>next<\/code>.<\/li><\/ul>\n\n\n\n<p><strong>Follow up:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Could you implement&nbsp;<code>next()<\/code>&nbsp;and&nbsp;<code>hasNext()<\/code>&nbsp;to run in average&nbsp;<code>O(1)<\/code>&nbsp;time and use&nbsp;<code>O(h)<\/code>&nbsp;memory, where&nbsp;<code>h<\/code>&nbsp;is the height of the tree?<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Solution: In-order traversal using a stack<\/strong><\/h2>\n\n\n\n<p>Use a stack to simulate in-order traversal.<\/p>\n\n\n\n<p>Each next, we walk to the left most (smallest) node and push all the nodes along the path to the stack.<\/p>\n\n\n\n<p>Then pop the top one t as return val, our next node to explore is the right child of t.<\/p>\n\n\n\n<p>Time complexity: amortized O(1) for next() call.<br>Space complexity: O(n)<\/p>\n\n\n\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">C++<\/h2>\n<div class=\"tabcontent\">\n\n<pre lang=\"c++\">\n\/\/ Author: Huahua\n\/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n *\/\nclass BSTIterator {\npublic:\n  BSTIterator(TreeNode* root) : root_(root) {}\n\n  int next() {\n    while (root_) {\n      s_.push(root_);\n      root_ = root_->left;\n    }\n    TreeNode* t = s_.top(); s_.pop();\n    root_ = t->right;\n    return t->val;\n  }\n\n  bool hasNext() {\n    return (root_ || !s_.empty());\n  }\nprivate:\n  TreeNode* root_;\n  stack<TreeNode*> s_;\n};\n\n\/**\n * Your BSTIterator object will be instantiated and called as such:\n * BSTIterator* obj = new BSTIterator(root);\n * int param_1 = obj->next();\n * bool param_2 = obj->hasNext();\n *\/\n<\/pre>\n<\/div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Implement the&nbsp;BSTIterator&nbsp;class that represents an iterator over the&nbsp;in-order traversal&nbsp;of a binary search tree (BST): BSTIterator(TreeNode root)&nbsp;Initializes an object of the&nbsp;BSTIterator&nbsp;class. The&nbsp;root&nbsp;of the BST is given&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[45],"tags":[737,177,179,180,28],"class_list":["post-8908","post","type-post","status-publish","format-standard","hentry","category-tree","tag-in-order","tag-medium","tag-simulation","tag-stack","tag-tree","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/8908","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=8908"}],"version-history":[{"count":2,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/8908\/revisions"}],"predecessor-version":[{"id":8910,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/8908\/revisions\/8910"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=8908"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=8908"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=8908"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}