包含min函数的栈
题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
解法一:双栈法
- 双栈
public class Solution {
private Stack<Integer> s1 = new Stack();
private Stack<Integer> s2 = new Stack();
public void push(int node) {
s1.push(node);
if(s2.isEmpty() || node < s2.peek()){
s2.push(node);
}else{
s2.push(s2.peek());
}
}
public void pop() {
s1.pop();
s2.pop();
}
public int top() {
return s1.peek();
}
public int min() {
return s2.peek();
}
}
栈的压入、弹出序列
题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
解法一:使用辅助栈
- 把入栈元素依次压栈,然后每次判断当前元素与pop栈中的最上面的元素是否相同,相同的话,弹出栈顶元素,然后pop栈的元素位置向后移动。接着判断该元素是否与栈顶元素相同。
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
if(pushA == null || pushA.length == 0 || popA == null ||
popA.length == 0){
return false;
}
Stack<Integer> s = new Stack();
int popIndex = 0;
for(int i = 0;i< pushA.length;i++){
s.push(pushA[i]);
while(!s.isEmpty() && s.peek() == popA[popIndex]){
s.pop();
popIndex++;
}
}
return s.isEmpty();
}
}
从上往下打印二叉树
题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
解法一:
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> res = new ArrayList();
if(root == null){
return res;
}
Queue<TreeNode> queue = new LinkedList();
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
for(int i = 0;i<size;i++){
TreeNode cur = queue.poll();
res.add(cur.val);
if(cur.left != null){
queue.offer(cur.left);
}
if(cur.right != null){
queue.offer(cur.right);
}
}
}
return res;
}
}
二叉搜索树的后序遍历序列
题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
解法一:
public boolean VerifySquenceOfBST(int [] sequence) {
if(sequence == null || sequence.length <= 0){
return false;
}
return isPost(sequence, 0, sequence.length-1);
}
public boolean isPost(int[] sequence, int start, int end){
if(end <= start){
return true;
}
int root = sequence[end];
//在二叉搜索树中找左子树比根节点大的值
int i = start;
for(;i<end;i++){
if(sequence[i] > root){
break;
}
}
//在右子树找到比根节点小的值
for(int j = i;j < end;j++){
if(sequence[j] < root){
return false;
}
}
return isPost(sequence, start, i-1) && isPost(sequence, i, end-1);
}
二叉树中和为某一值的路径
题目描述
输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
解法一:
public class Solution {
ArrayList<Integer> list = new ArrayList<>();
ArrayList<ArrayList<Integer>> res = new ArrayList();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(root == null){
return res;
}
list.add(root.val);
target -= root.val;
if(target == 0 && root.left == null && root.right == null){
res.add(new ArrayList(list));
}
FindPath(root.left, target);
FindPath(root.right, target);
list.remove(list.size() - 1);
return res;
}
}