二叉树最大宽度

给定一个二叉树,编写一个函数来获取这个树的最大宽度。树的宽度是所有层中的最大宽度。这个二叉树与满二叉树(full binary tree)结构相同,但一些节点为空。

每一层的宽度被定义为两个端点(该层最左和最右的非空节点,两端点间的null节点也计入长度)之间的长度。

示例 1:

输入:

输出: 4

解释: 最大值出现在树的第 3 层,宽度为 4 (5,3,null,9)。

示例 2:

输入:

输出: 2

解释: 最大值出现在树的第 3 层,宽度为 2 (5,3)。

示例 3:

输入:

输出: 2

解释: 最大值出现在树的第 2 层,宽度为 2 (3,2)。

示例 4:

输入:

输出: 8

解释: 最大值出现在树的第 4 层,宽度为 8 (6,null,null,null,null,null,null,7)。

注意: 答案在32位有符号整数的表示范围内。

思路

pproach Framework

Explanation

As we need to reach every node in the given tree, we will have to traverse the tree, either with a depth-first search, or with a breadth-first search.

The main idea in this question is to give each node a position value. If we go down the left neighbor, then position -> position * 2; and if we go down the right neighbor, then position -> position * 2 + 1. This makes it so that when we look at the position values L and R of two nodes with the same depth, the width will be R - L + 1.

Intuition and Algorithm

Traverse each node in breadth-first order, keeping track of that node's position. For each depth, the first node reached is the left-most, while the last node reached is the right-most.

 class Solution {
public int widthOfBinaryTree(TreeNode root) {
Queue<AnnotatedNode> queue = new LinkedList();
queue.add(new AnnotatedNode(root, 0, 0));
int curDepth = 0, left = 0, ans = 0;
while (!queue.isEmpty()) {
AnnotatedNode a = queue.poll();
if (a.node != null) {
queue.add(new AnnotatedNode(a.node.left, a.depth + 1, a.pos * 2));
queue.add(new AnnotatedNode(a.node.right, a.depth + 1, a.pos * 2 + 1));
if (curDepth != a.depth) {
curDepth = a.depth;
left = a.pos;
}
ans = Math.max(ans, a.pos - left + 1);
}
}
return ans;
}
} class AnnotatedNode {
TreeNode node;
int depth, pos;
AnnotatedNode(TreeNode n, int d, int p) {
node = n;
depth = d;
pos = p;
}
}

最新文章

  1. 【转】微软教学:三种方法屏蔽Win7/Win8.1升级Win10推送
  2. JavaScript中的防篡改对象
  3. Eclipse下Android开发的问题:Failed to install AndroidPhone.apk on device &#39;emulator-5554&#39;: timeout 解决办法
  4. win7打开网页老是提示下载网页解决办法
  5. jsp页面 直接从地址栏中 获取 参数的方法
  6. UBIFS FAQ and HOWTO
  7. 【linux命令】打开关闭防火墙iptables
  8. 《并行程序设计导论》——OpenMP
  9. redis的数据持久化方案
  10. 【HANA系列】SAP HANA XS使用JavaScript编程详解
  11. FFmpeg 结构体学习(三): AVPacket 分析
  12. 【重磅干货整理】机器学习(Machine Learning)与深度学习(Deep Learning)资料汇总
  13. [THUWC2017]在美妙的数学王国中畅游
  14. JSON必知必会,浅尝辄止的整理
  15. django之路由分析
  16. 计算图 graph
  17. TrID文件类型识别linux版
  18. 深入理解java虚拟机(六)字节码指令简介
  19. Linux——ps(列出进程)
  20. div清空填充

热门文章

  1. C# as运算符
  2. 概述「DAG加边至强连通」模型&amp;&amp;luoguP2746校园网Network of Schools
  3. 面试题 LazyMan 的Rxjs实现方式
  4. vue数据绑定html
  5. ubuntu18.04.1LTS系统远程工具secureCRT
  6. centos7重启apache、nginx、mysql、php-fpm命令
  7. 【js】【跨域问题】前后端分离的跨域问题
  8. MySQL Limit 限定查询记录数
  9. spark练习---ip匹配以及广播的特性
  10. 跨域携带cookie