[leetcode] 173. Binary Search Tree Iterator

Description

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling next() will return the next smallest number in the BST.

Example:
bst-tree

BSTIterator iterator = new BSTIterator(root);
iterator.next();    // return 3
iterator.next();    // return 7
iterator.hasNext(); // return true
iterator.next();    // return 9
iterator.hasNext(); // return true
iterator.next();    // return 15
iterator.hasNext(); // return true
iterator.next();    // return 20
iterator.hasNext(); // return false

Note:

  • next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
  • You may assume that next() call will always be valid, that is, there will be at least a next smallest number in the BST when next() is called.

分析

题目的意思是:
实现一个二叉搜索树的遍历迭代器,其中要有next(),hasNext()函数,要求时间复杂度为O(1), 空间复杂度为O(h),h为树的高度。

-这道题我不会,结果看别人的解析,用一个栈就能解决,我要哭了。
初始化的时候,把二叉树遍历root->left压入栈中,
next函数的实现:
把栈顶的元素输出,如果出栈的元素有右分支,把t->right,遍历t->left押入栈中。
hasNext():
判断一下节点是否为空就行了。

  • 如果读者还是不理解,就直接看代码手动模拟吧,栈能够保证遍历按照从小到大输出。

C++实现

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
private:
    stack<TreeNode*> s;
public:
    BSTIterator(TreeNode *root) {
        while(root){
            s.push(root);
            root=root->left;
        }
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        return !s.empty();
    }

    /** @return the next smallest number */
    int next() {
        TreeNode* t=s.top();
        s.pop();
        int res=t->val;
        if(t->right){
            t=t->right;
            while(t){
                s.push(t);
                t=t->left;
            }
        }
        return res;
    }
};

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */

Python实现

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class BSTIterator:
    def inorder(self, root, res):
        if root is None:
            return 
        self.inorder(root.left, res)
        res.append(root)
        self.inorder(root.right, res)

    def __init__(self, root: Optional[TreeNode]):
        self.res = []
        self.inorder(root,self.res)
        self.idx = 0
    def next(self) -> int:
        if self.idx < len(self.res):
            val = self.res[self.idx].val
            self.idx+=1
            return val



    def hasNext(self) -> bool:
        if self.idx<len(self.res):
            return True
        else:
            return False



# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()

参考文献

[LeetCode] Binary Search Tree Iterator 二叉搜索树迭代器

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值