1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 11 public class BSTIterator { 12 private Stack<TreeNode> stack; 13 14 private void initialNode(TreeNode root) { 15 while (root != null) { 16 stack.push(root); 17 root = root.left; 18 } 19 } 20 public BSTIterator(TreeNode root) { 21 stack = new Stack<>(); 22 initialNode(root); 23 } 24 25 /** @return whether we have a next smallest number */ 26 public boolean hasNext() { 27 return stack.size() > 0; 28 } 29 30 /** @return the next smallest number */ 31 public int next() { 32 TreeNode root = stack.pop(); 33 if (root.right != null) { 34 initialNode(root.right); 35 } 36 return root.val; 37 } 38 } 39 40 /** 41 * Your BSTIterator will be called like this: 42 * BSTIterator i = new BSTIterator(root); 43 * while (i.hasNext()) v[f()] = i.next(); 44 */
二叉搜索树迭代器实现
本文介绍了一种二叉搜索树迭代器的实现方法,该迭代器能够按顺序访问二叉搜索树中的所有节点。文章提供了一个使用栈来保存遍历路径的类,通过不断将左子节点压入栈中直到为空,再从栈顶取出节点并遍历其右子树的方式实现了迭代器的hasNext和next方法。
817

被折叠的 条评论
为什么被折叠?



