有苦有乐的算法 --- 获取二叉树的最大宽度

题目

一颗二叉树,求其最大宽度。
例:

解析

按层遍历二叉树;
在遍历时,使用用4个变量来记录信息;
Node curEnd = null; // 当前层,最右节点是谁
Node nextEnd = null; // 下一层,最右节点是谁
int max = 0; // 暂时最大宽度
int curLevelNodes = 0; // 当前层的节点数

头结点入队,curEnd = 头结点;nextEnd = 头结点的右节点;
头结点出队,curLevelNodes ++,此时 出队节点==curEnd, max = 当前curLevelNodes ,curLevelNodes 重新=0,curEnd = nextEnd ,nextEnd = null ;

出队一个节点,curLevelNodes ++,nextEnd =出队节点的右节点,右节点为空 nextEnd =出队节点的左节点 ,右节点和左节点都为空 nextEnd 不变, 当出队节点==curEnd时,max = max(curLevelNodes,max),curLevelNodes 重新=0,curEnd = nextEnd ,nextEnd = null ;

以此类推:

此时max为最大宽度;

代码

public static class Node {
	public int value;
	public Node left;
	public Node right;
	public Node(int data) {
		this.value = data;
	}
}

public static int maxWidth(Node head) {
	if (head == null) {
		return 0;
	}
	Queue<Node> queue = new LinkedList<>();
	queue.add(head);
	Node curEnd = head; // 当前层,最右节点是谁
	Node nextEnd = null; // 下一层,最右节点是谁
	int max = 0; // 暂时最大宽度
	int curLevelNodes = 0; // 当前层的节点数
	while (!queue.isEmpty()) {
		Node cur = queue.poll();
		if (cur.left != null) {
			queue.add(cur.left);
			nextEnd = cur.left;
		}
		if (cur.right != null) {
			queue.add(cur.right);
			nextEnd = cur.right;
		}
		curLevelNodes++;
		if (cur == curEnd) {
			max = Math.max(max, curLevelNodes);
			curLevelNodes = 0;
			curEnd = nextEnd;
		}
	}
	return max;
}
posted @ 2022-03-07 18:03  叕叕666  阅读(66)  评论(0)    收藏  举报