常见算法题4

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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值