173. 二叉搜索树迭代器
题目链接
https://leetcode-cn.com/problems/binary-search-tree-iterator/
做法1
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ /** * 利用二叉搜索树的性质, 每次弹出左子树的左节点,这样子可以保证每次弹出都是最小的数 */ class BSTIterator { private Stack<TreeNode> stack = new Stack<>(); public BSTIterator(TreeNode root) { pushAll(root); } /** @return whether we have a next smallest number */ public boolean hasNext() { return !stack.isEmpty(); } /** @return the next smallest number */ public int next() { TreeNode treeNode = stack.pop(); pushAll(treeNode.right); return treeNode.val; } private void pushAll(TreeNode treeNode){ for (; treeNode != null; stack.push(treeNode), treeNode = treeNode.left); } } /** * Your BSTIterator object will be instantiated and called as such: * BSTIterator obj = new BSTIterator(root); * int param_1 = obj.next(); * boolean param_2 = obj.hasNext(); */
做法2
/** * 做法2 利用中序遍历,从小到大取出所有节点 */ class BSTIterator { private Stack<TreeNode> stack = new Stack<>(); public BSTIterator(TreeNode root) { while (root != null){ stack.push(root); if (root.left != null){ root = root.left; } else break; } } /** @return the next smallest number */ public int next() { TreeNode root =stack.pop(); TreeNode res = root; if (res.right != null){ res = res.right; while (res != null){ stack.push(res); if (res.left != null) res = res.left; else break; } } return root.val; } /** @return whether we have a next smallest number */ public boolean hasNext() { return !stack.isEmpty(); } }
浙公网安备 33010602011771号