Enter two integer sequences. The first sequence represents the push order of the stack. Please judge whether the second sequence is the pop-up order of the stack. Assume that all the numbers pushed into the stack are not equal. For example, sequence 1,2,3,4,5 is the pressing sequence of a stack, sequence 4,5,3,2,1 is a pop-up sequence corresponding to the pressing sequence, but 4,3,5,1,2 cannot be the pop-up sequence of the pressing sequence. (Note: the two sequences are the same length)
import java.util.*; public class Solution { public boolean IsPopOrder(int [] pushA,int [] popA) { if(pushA==null || popA==null) return false; Stack<Integer> stack = new Stack<>(); int k=0; for (int i = 0; i < pushA.length; i++) { stack.push(pushA[i]); while(!stack.empty() && stack.peek() == popA[k]){ stack.pop(); k++; } } return stack.empty(); } }
Each node of the binary tree is printed from top to bottom, and the nodes of the same layer are printed from left to right.
public class Solution { public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) { ArrayList<Integer> arr = new ArrayList<>(); if(root == null) return arr; Deque<TreeNode> que = new LinkedList<>(); que.add(root); while(!que.isEmpty()){ TreeNode a = que.pop(); arr .add(a.val); if(a.left!=null) que.add(a.left); if(a.right!=null) que.add(a.right); } return arr; } }
Input an integer array to determine whether the array is the result of the subsequent traversal of a binary search tree. If Yes, output Yes; otherwise, output No. Suppose that any two numbers of the input array are different from each other.
public class Solution { public boolean VerifySquenceOfBST(int [] sequence) { if(sequence.length ==0) return false; return IsTreeBST(sequence, 0, sequence.length-1); } private boolean IsTreeBST(int[] sequence, int start, int end) { if(start>=end) return true; int i; for (i=start; i < end; i++) { if(sequence[i] >sequence[end]) break; } for (int j = i; j < end; j++) { if(sequence[j] < sequence[end]) return false; } return IsTreeBST(sequence,start,i-1) && IsTreeBST(sequence,i,end-1); } }