1. 选取栈内最小值
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
采用了双栈的思想,一个栈放历代的最小值,里一个栈存储所有的数值
import java.util.Stack;
public class Solution {
Stack<Integer> minstack = new Stack<Integer>();
Stack<Integer> stack = new Stack<Integer>();
Integer temp = null;
public void push(int node) {
if(temp != null){
if(node < temp){
minstack.push(node);
temp = node;
}
stack.push(node);
}else{
minstack.push(node);
temp = node;
stack.push(node);
}
}
public void pop() {
int num1 = stack.pop();
int num2 = minstack.pop();
if(num1 != num2)
minstack.push(num2);
}
public int top() {
int num = stack.pop();
stack.push(num);
return num;
}
public int min() {
int minTop = minstack.pop();
minstack.push(minTop);
return minTop;
}
}
2. 判断栈的压入弹出序列
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
利用栈的特性
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
if(pushA.length == 0 || popA.length == 0)
return false;
Stack<Integer> s = new Stack<Integer>();
int popIndex = 0;
for(int i=0; i<pushA.length; i++){
s.push(pushA[i]);
while(!s.empty() && s.peek() == popA[popIndex]){
s.pop();
popIndex++;
}
}
return s.empty();
}
}
3. 层次遍历打印节点
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
引用队列的特性,Queue要通过LinkedList来实现
import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<Integer> result = new ArrayList<Integer>();
Queue<TreeNode> que = new LinkedList<TreeNode>();
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
if(root != null){
que.offer(root);
while(!que.isEmpty()){
TreeNode parent = que.poll();
result.add(parent.val);
if(parent.left!=null)
que.offer(parent.left);
if(parent.right!=null)
que.offer(parent.right);
}
}
return result;
}
}
4. 判断是否为二叉搜索树的后序遍历
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
递归
public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
if(sequence.length == 0) return false;
if(sequence.length == 1) return true;
return judge(sequence, 0, sequence.length-1);
}
public boolean judge(int [] array, int start, int end){
if(start>=end) return true;
int root = array[end], i;
for(i=start; i<end; i++){
if(array[i]>root)
break;
}
for(int j=start; j<i-1; j++)
if(array[j]>array[end]) return false;
for(int j=i; j<end; j++)
if(array[j]<array[end]) return false;
return judge(array, start, i-1)&&judge(array, i, end-1);
}
}