我做了LeetCode问题Binary Search Tree Iterator。以下代码是我从别人那里学到的。我不明白哪一部分是cur = cur.right。因为我得到了cur.val的最小值。为什么我需要将cur.right分配给cur?当我删除cur = cur.right时,它表示超出了时间限制。有人可以帮我解释一下吗?
public class BSTIterator {
Stack<TreeNode> stack;
TreeNode cur;
public BSTIterator(TreeNode root) {
stack = new Stack<>();
cur = root;
}
/** @return the next smallest number */
public int next() {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
int val = cur.val;
cur = cur.right; //why needed to assign cur.right to cur?
return val;
}
}
答案 0 :(得分:0)
通过考虑二叉搜索树的结构,我们知道左边节点小于父节点(或中节点节点),右边节点比父节点(或中间节点)多。通过将当前节点设置为等于右节点,您将按从最小值到最大值的顺序迭代树。请注意,如果cur.right()不存在,那么cur将被设置为null,因此不会执行while循环。
答案 1 :(得分:0)
我提交了代码,成功了。 https://leetcode.com/problems/binary-search-tree-iterator/
说明。 您必须使用 inorder ,该方法首先访问左子树,然后访问当前节点,然后访问右子树,以便您将按升序遍历所有元素。>
现在,您有了堆栈,该堆栈包含应按正确顺序在next
调用中返回的所有节点。
next
将删除堆栈中的最后一个元素。现在,您检查当前节点是否具有正确的子树。如果是这样,则需要遍历右侧子树的左侧元素。
/**
* Find next node to be returned in {@link #next()}.
* Push it to stack.
*/
public void navigateLeftSubtree() {
stack.push(currentNode);
while (currentNode.left != null) {
currentNode = currentNode.left;
stack.push(currentNode);
}
}
在这种情况下,(当前节点存在右子树),应将当前节点的右子节点放入堆栈中。如果您已经访问过电流,则不想将其放入堆栈中。
public int next() {
currentNode = stack.pop();
final int currentValue = currentNode.value;
if (currentNode.right != null) {
// Push root of the right subtree into stack.
currentNode = currentNode.right;
navigateLeftSubtree();
}
return currentValue;
}