Java实现广度遍历二叉树2

标题:Java实现广度遍历二叉树2

//12.6
/*
题目:二叉树的层次遍历
*/
/*
方法一:迭代
*/
 public List<List<Integer>> levelOrder(TreeNode head){
	List<List<Integer>> alist = new ArrayList<>();
	if(head == null){
		return alist;
	}
	
	Queue<TreeNode> q = new LinkedList<>();
	q.offer(head);
	
	while(!q.isEmpty()){
		int size = q.size();
		List<Integer> blist = new ArrayList<>();
		for(int i = 0; i < size;i++){
			TreeNode p = q.poll();
			blist.add(p.val);
			if(p.left != null){
				q.offer(p.left);
			}
			if(p.right != null){
				q.offer(p.right);
			}
		}
		alist.add(blist);
	}
	
	return alist;
}

/*
方法二:递归
*/
public List<List<Integer>> levelOrder(TreeNode head){
	List<List<Integer>> alist = new ArrayList<>();
	if(head == null){
		return alist;
	}
	
	Queue<TreeNode> q = new LinkedList<>();
	q.offer(head);
	
	this.level(q, alist, new ArrayList<>(), 1);
	
	return alist;
}
public void level(Queue<TreeNode> q, List<List<Integer>> alist, List<Integer> blist, int count){
	if(q.isEmpty()){
		return ;
	}else{
		TreeNode p = q.poll();
		if(p.left != null){
			q.offer(p.left);
		}
		if(p.right != null){
			q.offer(p.right);
		}
		
		count--;
		blist.add(p.val);
		if(count == 0){
			alist.add(blist);
			blist = new ArrayList<>();
			count = q.size();
		}
		this.level(q, alist, blist, count);
	}
}

/*
方法三:递归,(dfs)
*/
public List<List<Integer>> levelOrder(TreeNode head){
	List<List<Integer>> alist = new ArrayList<>();
	if(head == null){
		return alist;
	}
	
	Queue<TreeNode> q = new LinkedList<>();
	q.offer(head);
	
	this.level(head, alist, 0);
	
	return alist;
}
public void level(TreeNode root, List<List<Integer>> alist, int index){
	if(root == null){
		return ;
	}
	if(index >= alist.size()){
		alist.add(new ArrayList<>());
	}
	alist.get(index).add(root.val);
	
	if(root.left != null){
		this.level(root.left, alist, index + 1);
	}
	if(root.right != null){
		this.level(root.right, alist, index + 1);
	}
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值