Tree——No.173 Binary Search Tree Iterator

Problem:

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.

Explanation:

设计一个迭代器,next()方法可以获得二叉树中下一个最小的元素,hasnext()方法用于判断是否有下一个最小元素。

My Thinking:

维护一个中序遍历的list以及当前元素的index

My Solution:

class BSTIterator {
    private List<Integer> list=new ArrayList<>();
    private int index=0;
    public BSTIterator(TreeNode root) {
        inorderTraverse(root);
    }
    
    public void inorderTraverse(TreeNode root){
        if(root==null)
            return;
        inorderTraverse(root.left);
        list.add(root.val);
        inorderTraverse(root.right);
    }
    
    /** @return the next smallest number */
    public int next() {
        return list.get(index++);
    }
    
    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return index<list.size();
    }
}

Optimum Thinking:

使用栈先存放所有左结点,每次弹出一个结点再将其右孩子入栈,同时返回当前结点的值

Optimum Solution:

public class BSTIterator {
    private Stack<TreeNode> stack = new Stack<TreeNode>();
    
    public BSTIterator(TreeNode root) {
        pushAll(root);
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return !stack.isEmpty();
    }

    /** @return the next smallest number */
    public int next() {
        TreeNode tmpNode = stack.pop();
        pushAll(tmpNode.right);
        return tmpNode.val;
    }
    
    private void pushAll(TreeNode node) {
        while(node!=null){
            stack.push(node);
            node = node.left;
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值