21. Enter a sequence of two integers, the first sequence indicates the stacking order of the stack, and determine if the second sequence is the pop-up order for the stack. Assume that all the numbers that are pressed into the stack are not equal. For example, the sequence 1,2,3,4,5 is the indentation order of a stack, and the sequence 4,5,3,2,1 is a pop-up sequence corresponding to the stack sequence, but 4,3,5,1,2 is not likely to be the pop-up sequence of the stack sequence. (Note: The lengths of the two sequences are equal)
ImportJava.util.Stack; Public classSolution { Public BooleanIspoporder (int[] Pusha,int[] PopA) {Stack s=NewStack (); inti = 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. From top to bottom, print out each node of the two-fork tree, and the same layer node prints from left to right.
Importjava.util.ArrayList;ImportJava.util.Queue;Importjava.util.LinkedList;/**Public class TreeNode {int val = 0; TreeNode left = null; TreeNode right = null; Public TreeNode (int val) {this.val = val; }}*/ Public classSolution { PublicArraylist<integer>printfromtoptobottom (TreeNode root) {ArrayList<Integer> treelist =NewArraylist<integer>();
It is important to note that the queue is an interface and cannot create an instance of the queue directly, only subclass queue that implements the queue interface<TreeNode> q =NewLinkedlist<treenode>(); Q.offer (root); if(Root = =NULL){ returntreelist; } 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); } returntreelist; }}
java--Sword Point Offer (5)