# leetcode 173. Binary Search Tree Iterator-二叉搜索树迭代|中序遍历

【思路-Java】中序遍历非递归实现

public class BSTIterator {
Stack<TreeNode> stack = new Stack<TreeNode>();
public BSTIterator(TreeNode root) {
while(root != null) {
root = root.left;
}
}

/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}

/** @return the next smallest number */
public int next() {
TreeNode temp = stack.pop();
int val = temp.val;
if(temp.right != null) {
temp = temp.right;
while (temp != null) {
temp = temp.left;
}
}
return val;
}
}
61 / 61 test cases passed. Runtime: 6 ms  Your runtime beats 78.97% of javasubmissions.

【思路2-Java】

public class BSTIterator {
TreeNode root = new TreeNode(0);
public BSTIterator(TreeNode root) {
this.root.right = root;
}

/** @return whether we have a next smallest number */
public boolean hasNext() {
return root.right != null;
}

/** @return the next smallest number */
public int next() {
TreeNode next = root.right;
if (next.left == null) {
root = next;
return next.val;
}
TreeNode right = root.right;
TreeNode parent = root;
while(next.left != null) {
parent = next;
next = next.left;
}
parent.left = next.right;
root.right = next;
next.right = right;
root = root.right;
return root.val;
}
}
61 / 61 test cases passed. Runtime: 5 ms  Your runtime beats 94.32% of javasubmissions.

• 本文已收录于以下专栏：

举报原因： 您举报文章：leetcode 173. Binary Search Tree Iterator-二叉搜索树迭代|中序遍历 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)