深度优先和广度优先 - java二叉树

本文介绍了二叉树的深度优先和广度优先遍历算法,提供了Java实现代码。深度优先包括前序遍历,广度优先则按层序输出节点。此外,还讨论了一个扩展问题,如何找出二叉树层数最多的节点数量,并给出了相应的解决方案。
摘要由CSDN通过智能技术生成

深度优先算法

二叉树中的深度优先算法就是先序遍历
代码如下:

public void N(Node head){
	Stack stack = new Stack<Node>();
	stack.push(head);
	while(!stack.isEmpty()){
		Node help = stack.pop();
		System.out.print(help.val + " ");
		if(help.right != null){
			stack.push(help.right); 
		} 
		if(help.left != null){
			stack.push(help.left); 
		} 
	}
	System.out.println();
}

广度优先算法

说白了就是一排一排的依次输出
代码如下:

public void f(Node head){
	Queue queue = new LinkedList();
	queue.add(head);
	while(!queue.isEmpty()){
		Node help = queue.poll();
		System.out.print(help.val + " ");
		 if(help.left!= null){
			queue.add(help.left); 
		} 
		if(help.right!= null){
			queue.add(help.right);
		} 
	}
	System.out.println();
}

做一个扩展题把,上述广度优先算法的应用——算出二叉数那一层的数最多
代码如下:

public int f(Node head){
	Queue queue = new LinkedList();
	queue.add(head);
	HashMap<Node , Integer> hashMap = new HashMap();
	hashMap.put(head , 1);
	int lever = 1;
	int Nodes = 0;
	int max = Integer.MIN_VALUE;
	while(!queue.isEmpty()){
		Node help = queue.poll();
		int curLever = hashMap.get(help);
		if(curLever == lever){
			Nodes++; 
			max = Math.max(max , Nodes);
		}else{
			
			lever++;
			Nodes = 1; 
		}
		 if(help.left!= null){
		 	hasMap.put(help.left , lever+1)
			queue.add(help.left); 
		} 
		if(help.right != null){
			hasMap.put(help.right, lever+1)
			queue.add(help.right);
		} 
	}
	System.out.println();
	return max;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值