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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BSTIterator { List<Integer> list = new ArrayList<Integer>();// 存放结点的值 Stack<TreeNode> st = new Stack<TreeNode>();// 遍历的过程中存放结点 public BSTIterator(TreeNode root) { if (root != null) st.push(root); } /** @return whether we have a next smallest number */ public boolean hasNext() { boolean flag1 = list.isEmpty(), flag2 = st.isEmpty(); if (!flag1) return true; if (flag1 && !flag2) return iteratorDemo(); return false; } /** @return the next smallest number */ public int next() { int num = list.get(0); list.remove(0); return num; } //中序遍历 public boolean iteratorDemo() { TreeNode top = null; while (!st.empty()) { top = st.peek(); while (top.left != null) { st.push(top.left); top = top.left; } while (top.right == null) { list.add(top.val); st.pop(); if (!st.empty()) top = st.peek(); else break; } if (!st.empty()) { list.add(top.val); st.pop(); st.push(top.right); break; } } if(list.isEmpty()) return false; return true; } } /** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */
leetcode_173_Binary Search Tree Iterator
原文地址:http://blog.csdn.net/mnmlist/article/details/44855551