标签:
21.输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
import java.util.Stack; public class Solution { public boolean IsPopOrder(int [] pushA,int [] popA) { Stack s = new Stack(); int i = 0,j = 0; s.push(pushA[i++]); if(pushA == null || popA == null){ return false; }else if(pushA.length == 0 || popA.length == 0){ return false; }else if(pushA.length != popA.length){ return false; }else{ while(j <= popA.length - 1){ while(popA[j] != s.peek()){ if(i == pushA.length){ return false; } s.push(pushA[i++]); } j++; s.pop(); } } return true; } }
22.从上往下打印出二叉树的每个节点,同层节点从左至右打印。
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 { public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) { ArrayList<Integer> treeList = new ArrayList<Integer>();
//这里要注意的是,Queue是一个接口,不能直接创建Queue的实例,只能创建实现Queue接口的子类 Queue<TreeNode> q = new LinkedList<TreeNode>(); q.offer(root); if(root == null){ return treeList; } while(!q.isEmpty()){ TreeNode temp = q.poll(); treeList.add(temp.val); if(temp.left != null) q.offer(temp.left); if(temp.right != null) q.offer(temp.right); } return treeList; } }
标签:
原文地址:http://www.cnblogs.com/wgl1995/p/5790866.html