18.二叉樹的鏡像
操作給定的二叉樹,將其變換為源二叉樹的鏡像。
輸入描述:
二叉樹的鏡像定義:源二叉樹
8
/
6 10
/ \ /
5 7 9 11
鏡像二叉樹
8
/
10 6
/ \ /
11 9 7 5
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public void Mirror(TreeNode root) {
root = Mirror1(root);
}
public TreeNode Mirror1(TreeNode root) {
if(root==null){
return null;
}
TreeNode left = root.left;
TreeNode right = root.right;
root.left = Mirror1(right);
root.right = Mirror1(left);
return root;
}
}
19.順時針打印矩陣
輸入一個矩陣,按照從外向里以順時針的順序依次打印出每一個數字,例如,如果輸入如下矩陣: 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.
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(matrix==null){
return list;
}
int row_len = matrix.length;
int col_len = matrix[0].length;
if(matrix.length *matrix[0].length ==0){
return list;
}
int[] res={col_len,row_len,-1,0};
int direction=0;
for(int i=0,j=0;;){
//向右
if(direction==0)
{
//添加該節點
list.add(matrix[i][j]);
//檢查下一個節點是否可以行走
if(j+1==res[direction]){//如果不可以
res[direction] = j;
//嘗試向下走
direction=1;
if(i+1==res[direction]){//如果不可以
return list;//結束
}else{
i++;
}
}else{
j++;
}
}else if(direction==1){//向下
//添加該節點
list.add(matrix[i][j]);
//檢查下一個節點是否可以行走
if(i+1==res[direction]){//如果不可以
res[direction] = i;
//嘗試向左走
direction=2;
if(j-1==res[direction]){//如果不可以
return list;
}else{
j--;
}
}else{
i++;
}
}else if(direction==2){//向左
//添加該節點
list.add(matrix[i][j]);
//檢查下一個節點是否可以行走
if(j-1==res[direction]){//如果不可以
res[direction] = j;
//嘗試向上走
direction=3;
if(i-1==res[direction]){//如果不可以
return list;
}else{
i--;
}
}else{
j--;
}
}else{//向上
//添加該節點
list.add(matrix[i][j]);
//檢查下一個節點是否可以行走
if(i-1==res[direction]){//如果不可以
res[direction] = i;
//嘗試向右走
direction=0;
if(j+1==res[direction]){//如果不可以
return list;
}else{
j++;
}
}else{
i--;
}
}
}
}
}
20.包含min函數的棧
定義棧的數據結構,請在該類型中實現一個能夠得到棧最小元素的min函數。
import java.util.Stack;
public class Solution {
int[] res=new int[100];
int top=0;
public void push(int node) {
res[top]=node;
top++;
}
public void pop() {
if(top>0){
top--;
}
}
public int top() {
if(top>0){
return res[top-1];
}
return 0;
}
public int min() {
int min=0;
if(top>0){
min=res[0];
}
for(int i=0;i<top;i++){
if(min> res[i]){
min =res[i];
}
}
return min;
}
}