next()
and hasNext()
queries run in O(1) time in average.Example 1java
Input: {10,1,11,#,6,#,12} Output: [1, 6, 10, 11, 12] Explanation: The BST is look like this: 10 /\ 1 11 \ \ 6 12 You can return the inorder traversal of a BST [1, 6, 10, 11, 12]
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } * Example of iterate a tree: * BSTIterator iterator = new BSTIterator(root); * while (iterator.hasNext()) { * TreeNode node = iterator.next(); * do something for node * } */ public class BSTIterator { private Stack<TreeNode> stack = new Stack<>(); // @param root: The root of binary tree. public BSTIterator(TreeNode root) { while (root != null) { stack.push(root); root = root.left; } } //@return: True if there has next node, or false public boolean hasNext() { return !stack.isEmpty(); } //@return: return next node public TreeNode next() { TreeNode curt = stack.peek(); TreeNode node = curt; // move to the next node if (node.right == null) { node = stack.pop(); while (!stack.isEmpty() && stack.peek().right == node) { node = stack.pop(); } } else { node = node.right; while (node != null) { stack.push(node); node = node.left; } } return curt; } }
Example 2node
Input: {2,1,3} Output: [1,2,3] Explanation: The BST is look like this: 2 / \ 1 3 You can return the inorder traversal of a BST tree [1,2,3]
Extra memory usage O(h), h is the height of the tree.算法
Super Star: Extra memory usage O(1)markdown
思路:app
这是一个很是通用的利用 stack 进行 Binary Tree Iterator 的写法。this
stack 中保存一路走到当前节点的全部节点,stack.peek() 一直指向 iterator 指向的当前节点。
所以判断有没有下一个,只须要判断 stack 是否为空
得到下一个值,只须要返回 stack.peek() 的值,并将 stack 进行相应的变化,挪到下一个点。code
挪到下一个点的算法以下:blog
访问全部节点用时O(n),因此均摊下来访问每一个节点的时间复杂度时O(1)ip