662. 二叉树最大宽度
给定一个二叉树,编写一个函数来获取这个树的最大宽度。树的宽度是所有层中的最大宽度。这个二叉树与满二叉树(full binary tree)结构相同,但一些节点为空。
每一层的宽度被定义为两个端点(该层最左和最右的非空节点,两端点间的null节点也计入长度)之间的长度。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-width-of-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.LinkedList;
class Solution {
public int widthOfBinaryTree(TreeNode root) {
if (root == null) {
return 0;
}
int ret = 0;
LinkedList<Info> queue = new LinkedList<>();
queue.offer(new Info(root, 0, 0));
Info left = null;
while (!queue.isEmpty()) {
Info info = queue.poll();
if (left == null || info.level != left.level) {
left = info;
}
ret = Math.max(ret, info.step - left.step + 1);
if (info.node.left != null) {
queue.offer(new Info(info.node.left, info.level + 1, info.step * 2 + 1));
}
if (info.node.right != null) {
queue.offer(new Info(info.node.right, info.level + 1, info.step * 2 + 2));
}
}
return ret;
}
}
class Info {
TreeNode node;
int level;
int step;
public Info(TreeNode node, int level, int step) {
this.node = node;
this.level = level;
this.step = step;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
心之所向,素履以往 生如逆旅,一苇以航

浙公网安备 33010602011771号