[LeetCode] 173. Binary Search Tree Iterator Java
题目:
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.
Note: next()
and hasNext()
should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
题意及分析:给出一个二叉排序树,求一个该二叉树的遍历器,满足:(1)hasNext()判断树中是否存在一个除了当前数的最小数。 (2)next()返回树中除了当前数的最小数。(3)要求o(1)的时间复杂度和o(h)的空间复杂度。使用一个栈保存即可,初始保存从根节点到最左节点的值,对于next,如果stack非空就存在hasnext smallest number;对于next,下一个最小的就是栈顶的值(因为该栈顶点的左子节点就是当前点,而栈顶点的右子树上的点肯定比栈顶点大),取出栈顶的点,然后对该点的右子节点左上面的操作(即遍历该点到该点的最左叶节点)。
代码:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BSTIterator { private Stack<TreeNode> stack; public BSTIterator(TreeNode root) { stack = new Stack<>(); TreeNode cur = root; while(cur != null){ stack.push(cur); if(cur.left != null) cur = cur.left; else break; } } /** @return whether we have a next smallest number */ public boolean hasNext() { return !stack.isEmpty(); } /** @return the next smallest number */ public int next() { TreeNode node = stack.pop(); TreeNode cur = node; // traversal right branch if(cur.right != null){ cur = cur.right; while(cur != null){ stack.push(cur); if(cur.left != null) cur = cur.left; else break; } } return node.val; } } /** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */