[LeetCode]Binary Search Tree Iterator
第一个解法用了一个HashMap 其实感觉比较笨的方法
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BSTIterator { TreeNode cur; TreeNode pre; HashMap<TreeNode, TreeNode> map = new HashMap<TreeNode, TreeNode>(); public BSTIterator(TreeNode root) { if (root == null) { return; } cur = root; while (cur.left != null) { map.put(cur, pre); pre = cur; cur = cur.left; } map.put(cur, pre); } /** @return whether we have a next smallest number */ public boolean hasNext() { return cur != null || pre != null; } /** @return the next smallest number */ public int next() { int result = cur.val; if (cur.right == null) { cur = pre; pre = map.get(cur); map.remove(cur); } else { cur = cur.right; map.put(cur, pre); while (cur.left != null) { map.put(cur.left, cur); cur = cur.left; } pre = map.get(cur); map.remove(cur); } return result; } } /** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */
下面这个用栈的方法明显思路清晰很多了
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BSTIterator { Stack<TreeNode> stack = new Stack<TreeNode>(); public BSTIterator(TreeNode root) { while (root != null) { stack.push(root); root = root.left; } } /** @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(); int result = node.val; node = node.right; while (node != null) { stack.push(node); node = node.left; } return result; } } /** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */