您的位置:首页 > 编程语言 > Java开发

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

2016-06-01 11:37 591 查看
原题链接:173. Binary Search Tree Iterator
【思路-Java】中序遍历非递归实现

我们知道二叉搜索树当前节点值总是大于左子树上的任一节点值,总是大于右子树上的任一节点值。要从小到大取出该节点,我们可以采用二叉树的中序遍历,该思路借用一个栈来实现,如果对二叉树的中序遍历思路不是很清晰的,可以参考我的另一篇博文:leetcode 94. Binary Tree
Inorder Traversal-中序遍历|递归|非递归public class BSTIterator {
Stack<TreeNode> stack = new Stack<TreeNode>();
public BSTIterator(TreeNode root) {
while(root != null) {
stack.add(root);
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) {
stack.add(temp);
temp = temp.left;
}
}
return val;
}
}61 / 61 test
cases passed. Runtime: 6
ms  Your runtime beats 78.97% of javasubmissions.

【思路2-Java】

如果我们打破常规,不用栈来实现,那么我们就需要变换策略,需要申请几枚指针:



该思路就是借助指针,逐一将最左端的点加到 root 指针的右边

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java leetcode