1.树的层次遍历
ArrayList<Integer> list =new ArrayList<Integer>();
public static void levelTravel(TreeNode root){
if(root==null) return list;
Queue<TreeNode> queue =new LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()){
TreeNode t=queue.poll();
list.add(temp.val);
if(t.left!=null) queue.add(t.left);
if(t.right!=null) queue.add(t.right);
}
}
2.反转二叉树
public TreeNode invertTree(TreeNode root){
if(root==null) return null;
TreeNode temp =root.left;
root.left=root.right;
root.right=temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
3.判断是否是对称二叉树
public boolean isSymmetric(TreeNode root){
if(root==null) return true;
return compare(root.left,root.right);
}
private boolean compare(TreeNode left,TreeNode right){
if(left==null&&right!=null) return false;
if(left!=null&&right==null) return false;
if(left==null&&right==null) return true;
if(left.val==right.val)
return compare(left.left,right.right)&&compare(left.right,right.left);
}
4.二分查找
public static int binarySearch(int[] arr,int des){
int low=0;
int high=arr.length-1;
while(low<=high){
int middle=(low+high)/2;
if(arr[middle]==des){
return middle;
}else if(arr[middle]>des){
high=middle-1;
}else{
low=middle+1;
}
}
return -1;
}
5.快速排序
public void quickSort(int arr[],int low,int high){
int start=low;
int end=high;
int key=arr[low];
while(end>start){
while(end>start&&arr[end]>=key){
end--
}
if(arr[end]<=key){
int temp=arr[end];
arr[end]=arr[start];
arr[start]=temp;
}
while(end>statr&&arr[end]<=key){
start++;
}
if(arr[end]>=key){
int temp=arr[start];
arr[start]=arr[end];
arr[end]=temp;
}
if(start>low){
quickSort(arr,low,start-1);
}
if(end<high){
quickSort(arr,end+1,high);
}
}
}
6.给定一个二叉树,求树中两个指定节点的最近公共祖先
public TreeNode lowestAncestor(TreeNode root,TreeNode p,TreeNode q){
if(root==null) return null;
if(root==p||root==q) return root;
TreeNode left=lowestAncestor(root.left,p,q);
TreeNode right=lowestAncestor(root.right,p,q);
if(left!=null&&right!=null) return root;
if(left!=null) return left;
if(right!=null) return right;
return null;
}