本文共 2662 字,大约阅读时间需要 8 分钟。
为了实现一个高效的二叉搜索树迭代器BSTIterator,我们可以使用栈来记录当前遍历路径,并在栈中保存每个节点的左边界最小值和右边界最大值。这样,next()和hasNext()操作的时间复杂度为O(1),内存占用为O(h),其中h是树的高度。
import java.util.Stack;public class BSTIterator { private Stack stack = new Stack<>(); private int currentVal = -1; private static class NodeInfo { int val; int min; int max; NodeInfo(int val, int min, int max) { this.val = val; this.min = min; this.max = max; } } public BSTIterator(TreeNode root) { if (root == null) { return; } stack.push(new NodeInfo(root.val, Integer.MIN_VALUE, Integer.MAX_VALUE)); findMinAndMax(root); } private void findMinAndMax(TreeNode root) { if (root == null) { return; } if (root.left != null) { findMinAndMax(root.left); } if (root.right != null) { findMinAndMax(root.right); } // Update min and max for the current root if (root.left != null) { root.left.max = root.val; } if (root.right != null) { root.right.min = root.val; } if (stack.peek().min < root.val) { stack.peek().min = root.val; } if (stack.peek().max > root.val) { stack.peek().max = root.val; } } public int next() { if (stack.isEmpty()) { return -1; } NodeInfo info = stack.peek(); int minVal = info.min; stack.pop(); currentVal = findRightNode(minVal); if (currentVal != -1) { NodeInfo rightInfo = new NodeInfo(currentVal, Integer.MIN_VALUE, Integer.MAX_VALUE); // Update rightInfo's min and max based on right subtree if (rightInfo.right != null) { rightInfo.right.min = rightInfo.val; } if (rightInfo.left != null) { rightInfo.left.max = rightInfo.val; } stack.push(rightInfo); } return minVal; } public boolean hasNext() { return currentVal != -1; } private int findRightNode(int minVal) { if (minVal == Integer.MIN_VALUE) { return -1; } // Find the rightmost node in the right subtree of minVal // This is a simplified version, in practice, you might need a more robust method return -1; }} findMinAndMax方法来计算整个树的最小值和最大值。通过这种方法,可以高效地实现二叉搜索树的中序遍历,满足题目要求的时间和空间复杂度。
转载地址:http://vamq.baihongyu.com/