二叉树求宽度以及宽度优先遍历

宽度优先遍历就是从上到下,从左到右依次遍历就行。

可以使用队列来做。

先将头结点放入队列,

重复下面的行为。

{从队列中弹出一个节点,并打印。

如果弹出的节点有左节点,就将左节点放入队列中,

如果弹出的节点有右节点,就将右节点放入队列中。先左后右。

}

	public static void widthPrioritySearch(NodeTwo node) {
		if(node==null) {
			return ;
		}
		Queue<NodeTwo> queue = new LinkedList<>();
		queue.add(node);
		while(!queue.isEmpty()) {
			NodeTwo cur = queue.poll();
			System.out.println(cur.value);
			if(cur.left != null) {
				queue.add(cur.left);
			}
			if(cur.right != null) {
				queue.add(cur.right);
			}
		}
	}

求二叉树的最大宽度:

思路:记录每一个节点所在的层,并且用一个变量记录每一层有多少个节点。

记录每一个节点所在的层最好使用的就是hash表。

			public static int widthMax(NodeTwo node) {
		if(node==null) {
			return 0;
		}
		Queue<NodeTwo> queue = new LinkedList<>();
		HashMap<NodeTwo,Integer> map = new HashMap<>();
		//使用hash表来记录每个节点所在的层数
		map.put(node, 1);
		int currentLevel = 1;
		int currentNodes = 0;
		int max = Integer.MIN_VALUE;
		queue.add(node);
		while(!queue.isEmpty()) {
			NodeTwo cur = queue.poll();
			int level = map.get(cur);
			if(currentLevel == level) {
				//弹出节点所在的层数等于现在的层数,
				//当前层数的节点数加1
				currentNodes++;
			}else {
				//如果弹出节点的层数不等于当前的层数
				//那么就是这个节点是下一层的了,上一层的节点个数已经统计好了
				max = Math.max(max, currentNodes);
				//
				currentLevel++;
				currentNodes = 1;
				//当前层的节点数置为1,
				
			}
//			System.out.println(cur.value);
			if(cur.left != null) {
				queue.add(cur.left);
				map.put(cur.left, map.get(cur)+1);
			}
			if(cur.right != null) {
				queue.add(cur.right);
				map.put(cur.right, map.get(cur)+1);
			}
		}
		//在最后一个节点弹出的时候有可能满足currentLevel == level
		//就不会将最后一层的节点数与最大值相比较
		//所以弹出所有节点之后需要再将最后一层的节点数和最大值进行比较
		return max = Math.max(max, currentNodes);
	}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值