剑指Offer面试题22栈的压入弹出序列,面试题23从上到下打印二叉树(层序遍历用队列)

面试题22:栈的压入弹出序列

输入两个整数序列,第一个序列表示压入顺序,判断第二个序列是否为弹出顺序.假设入栈所有数字均不相等。

思路:构建辅助栈,以压入序列1、2、3、4、5,弹出序列4、5、3、2、1为例,第一个弹出的是4,所以要先把4压入栈,此时栈里有1234,弹出栈顶即可,下一个弹出5,就依次压入直到5,弹出。

再举个反例,以弹出序列4、3、5、1、2为例,首先栈里有1234了,下一个弹出3,所以栈顶应该为3,但此时栈顶为4,所以不匹配。本题的Java实现:

public class IsPopOrder {
	static boolean ispoporder(int[] a,int[] b){
		if(a == null || b == null || a.length  != b.length){
			return false;
		}
		Stack<Integer> stack = new Stack<>();
		int pushIndex = 0;
		int popIndex = 0;
		boolean tag = false;
		while(popIndex < a.length){
			while(stack.isEmpty() || stack.peek() != b[popIndex]){//压入序列,直到当前弹出序列值和栈顶值相等。
				if(pushIndex == a.length){
					break;
				}
				stack.push(a[pushIndex]);
				pushIndex++;
			}
			if(stack.peek() != b[popIndex]){
				break;
			}
			stack.pop();
			popIndex++;
		}
		if(stack.isEmpty() && popIndex == a.length){
			tag = true;
		}
		return tag;
	}
	public static void main(String[] args){
		int[] a = {1,2,3,4,5};
		int[] b = {4,5,3,2,1};
		System.out.println(ispoporder(a, b));
	}
}

面试题23:从上到下打印二叉树(层序遍历用队列)

思路:树或图的层序遍历即广度优先遍历,用队列。本题Java实现如下:

public class PrintFromTopToBottom {
	static void printFromTopToBottom(BiTree root){
		if(root == null){
			return ;
		}
		Queue<BiTree> q = new LinkedList<>();
		q.offer(root);
		while(!q.isEmpty()){
			BiTree tree = q.poll();
			System.out.println(tree.value);
			if(tree.left != null){
				q.offer(tree.left);
			}
			if(tree.right != null){
				q.offer(tree.right);
			}
		}
	}
	public static void main(String[] args) {
		BiTree A1 = new BiTree(0);
		BiTree A2 = new BiTree(1);
		BiTree A3 = new BiTree(2);
		BiTree A4 = new BiTree(3);
		BiTree A5 = new BiTree(4);
		A1.left = A2;
		A1.right = A3;
		A2.left = A4;
		A2.right = A5;
		printFromTopToBottom(A1);
	}
}
class BiTree{
	int value;
	BiTree left;
	BiTree right;
	BiTree(int x){
		value = x;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值