JZ18.操作给定的二叉树,将其变换为源二叉树的镜像。
解题思路:遍历二叉树,同时调换各结点左右子树的位置,知道叶结点
BFS搜索,一层一层地访问
public TreeNode Mirror (TreeNode pRoot) {
// write code here
if(pRoot==null)
return null;
Queue<TreeNode> queue=new LinkedList<>();
queue.add(pRoot);
while(!queue.isEmpty()){
//获取队列头元素
TreeNode node=queue.poll();
TreeNode temp=node.left;
node.left=node.right;
node.right=temp;
if(node.left!=null){
queue.add(node.left);
}
if(node.right!=null){
queue.add(node.right);
}
}
return pRoot;
}
DFS遍历树
public TreeNode Mirror (TreeNode pRoot) {
// write code here
if(pRoot==null)
return null;
Stack<TreeNode> stack=new Stack<>();
stack.push(pRoot);
while(!stack.isEmpty()){
TreeNode node=stack.pop();
TreeNode temp=node.left;
node.left=node.right;
node.right=temp;
if(node.left!=null){
stack.push(node.left);
}
if(node.right!=null){
stack.push(node.right);
}
}
return pRoot;
}
JZ19.输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
解题思路:不断地收缩矩形的边界
定义四个变量:up,down,left,right;表示矩形的边界
向右走时,取整行的值,up+1,表示该行不会再被存入;
向下走时,取整列的值,right-1,表示该列不会再被存入;
向左走时,取整行的值,down-1,表示该行不会再被存入;
向上走时,取整列的值,left+1,表示该列不会再被存入;
每次存完一行或一列数据后,都要判断边界是否交错。
public ArrayList<Integer> printMatrix(int [][] matrix) {
ArrayList<Integer> list=new ArrayList<>();
if(matrix==null||matrix.length==0||matrix[0].length==0)
return list;
int up=0;
int down=matrix.length-1;
int left=0;
int right=matrix[0].length-1;
while(true){
for(int col=left;col<=right;col++){
list.add(matrix[up][col]);
}
up++;
if(up>down){
break;
}
for(int row=up;row<=down;row++){
list.add(matrix[row][right]);
}
right--;
if(left>right){
break;
}
for(int col=right;col>=left;col--){
list.add(matrix[down][col]);
}
down--;
if(up>down){
break;
}
for(int row=down;row>=up;row--){
list.add(matrix[row][left]);
}
left++;
if(left>right){
break;
}
}
return list;
}
JZ20. 定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数。在该栈中,调用 min、push 及 pop 函数的时间复杂度都是 O(1).
push(value):将元素 value压入栈中
pop():弹出栈顶的元素
top() :获得栈顶元素
min() :获得栈中的最小元素。
解题思路:要使调用min函数的时间复杂度为O(1),需要用空间换时间。开辟一个辅助栈,保证辅助栈顶元素是当前栈中最小的元素。如果辅助栈为空,直接压栈,如果元素小于等于辅助栈顶元素,直接压栈,否则将当前辅助栈顶元素压入辅助栈。
public class Solution {
Stack<Integer> normal=new Stack<Integer>();
Stack<Integer> min=new Stack<Integer>();
public void push(int node) {
normal.push(node);
if(min.empty()){
min.push(node);
}else{
if(node<=min.peek()){
min.push(node);
}else{
min.push(min.peek());
}
}
}
public void pop() {
normal.pop();
min.pop();
}
public int top() {
return normal.peek();
}
public int min() {
return min.peek();
}
}