leetcode [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.
Example:
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()
andhasNext()
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 whennext()
is called.
题目大意:
构造一个二叉树迭代器,按顺序返回二叉树的节点,next()函数得到二叉树的下一个节点,hasNext()判断是否有下一个节点。
解法:
其实就是按中序遍历的结果访问树的节点。我是将中序遍历的结果保存到一个数组中,然后按顺序返回数组中的值即可。
java:
class BSTIterator { List<Integer>l=new ArrayList<Integer>(); public void dfs(TreeNode node){ if(node==null) return; dfs(node.left); l.add(node.val); dfs(node.right); } public BSTIterator(TreeNode root) { dfs(root); } /** @return the next smallest number */ public int next() { int res=l.remove(0); return res; } /** @return whether we have a next smallest number */ public boolean hasNext() { return l.size()>0; } }
最佳的解法:
使用一个栈来保存树的左孩子。
java:
class BSTIterator { private Stack<TreeNode>s=new Stack<TreeNode>(); private void putAll(TreeNode node){ while(node!=null) { s.add(node); node=node.left; } } public BSTIterator(TreeNode root) { putAll(root); } /** @return the next smallest number */ public int next() { TreeNode tmpNode=s.pop(); if(tmpNode.right!=null) putAll(tmpNode.right); return tmpNode.val; } /** @return whether we have a next smallest number */ public boolean hasNext() { return !s.isEmpty(); } }