173. 二叉搜索树迭代器
解法一:
class BSTIterator {
private TreeNode node = new TreeNode();
private LinkedList<Integer> list = new LinkedList<>(); //从小到大依次入栈
public BSTIterator(TreeNode root) {
node = root;
list = order(node);
}
//用中序遍历将二叉树的值入栈
public LinkedList order(TreeNode root){
if(root==null)
return new LinkedList<>();
LinkedList<Integer> stack = new LinkedList<>();
if(root.left!=null)
stack.addAll(order(root.left));
if(root!=null)
stack.add(root.val);
if(root.right!=null)
stack.addAll(order(root.right));
return stack;
}
public int next() {
if(!list.isEmpty())
return list.pop(); //移除并返回栈顶
return 0;
}
public boolean hasNext() {
if(!list.isEmpty())
return true;
return false;
}
}
解法二:
class BSTIterator {
private Stack<TreeNode> stack = new Stack<TreeNode>();
public BSTIterator(TreeNode root) {
leftMost(root);
}
private void leftMost(TreeNode root) {
//将目前结点的所有左子树都依次入栈,即从大到小
while (root != null) {
stack.push(root);
root = root.left;
}
}
public int next() {
TreeNode node = stack.pop(); //此时栈顶是最小的元素,出栈
if (node.right != null) //如果该节点有右子树,就将右子树的所有左子树依次入栈
leftMost(node.right);
return node.val;
}
public boolean hasNext() {
if(!stack.isEmpty())
return true;
return false;
}
}
225.用队列实现栈
解法一:
class MyStack {
Queue<Integer> queue = new LinkedList<>();
public MyStack() {
}
public void push(int x) {
queue.add(x);
int size = queue.size();
while (size > 1) {
//将x前面的元素依次放在x后面,使队列的第一个元素为最后录入的那个元素
int top = queue.remove();
queue.add(top);
size --;
}
}
public int pop() {
return queue.remove();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.isEmpty();
}
}
解法二:
class MyStack {
private Queue<Integer> queue1 = new LinkedList<>();
private Queue<Integer> queue2 = new LinkedList<>();
public MyStack() {
}
public void push(int x) {
//将新加入的元素放在queue1中,再把queue2的所有元素出栈,添加到queue1中,保证后入的元素位于栈顶
queue1.add(x);
while (!queue2.isEmpty()) {
int top = queue2.remove();
queue1.add(top);
}
//交换1和2,保证1除了入栈以外都为空,2用来存储已入栈的元素
Queue temp = queue1;
queue1 = queue2;
queue2 = temp;
}
public int pop() {
return queue2.remove();
}
public int top() {
return queue2.peek();
}
public boolean empty() {
return queue2.isEmpty();
}
}
232.用栈实现队列
class MyQueue {
//stack1用来存储输入的元素
private Stack<Integer> stack1 = new Stack<>();
//stack2用来输出,先将1中的元素出栈到2中,这样顺序就颠倒了,再出栈就是先入先出了
private Stack<Integer> stack2 = new Stack<>();
public MyQueue() {
}
public void push(int x) {
stack1.push(x);
}
public int pop() {
//判断之前是否将1中元素传递到2中。若有,就先将之间的元素出栈完,再将1中元素传递过来
//同一个元素只存在一个栈中
if (stack2.empty()) {
int size = stack1.size();
while(size -- > 0)
stack2.push(stack1.pop());
}
return stack2.pop();
}
public int peek() {
if (stack2.empty()) {
int size = stack1.size();
while(size -- > 0)
stack2.push(stack1.pop());
}
return stack2.peek();
}
public boolean empty() {
//两栈都为空,才是真的空
return stack1.empty() && stack2.empty();
}
}