[LC] 173. Binary Search Tree Iterator
Posted xuanlu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LC] 173. Binary Search Tree Iterator相关的知识,希望对你有一定的参考价值。
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.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class BSTIterator { private LinkedList<TreeNode> stack; private TreeNode cur; public BSTIterator(TreeNode root) { stack = new LinkedList<>(); cur = root; } /** @return the next smallest number */ public int next() { while (cur != null) { stack.offerFirst(cur); cur = cur.left; } cur = stack.pollFirst(); int val = cur.val; cur = cur.right; return val; } /** @return whether we have a next smallest number */ public boolean hasNext() { return !stack.isEmpty() || cur != null; } } /** * Your BSTIterator object will be instantiated and called as such: * BSTIterator obj = new BSTIterator(root); * int param_1 = obj.next(); * boolean param_2 = obj.hasNext(); */
以上是关于[LC] 173. Binary Search Tree Iterator的主要内容,如果未能解决你的问题,请参考以下文章
173. Binary Search Tree Iterator - Unsolved
173.Binary search tree iterator
173. Binary Search Tree Iterator
leetcode@ [173] Binary Search Tree Iterator (InOrder traversal)