代码改变世界

Leetcode 662. 二叉树最大宽度

2019-10-22 22:06  tonyniu8  阅读(226)  评论(0)    收藏  举报

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

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

 

示例 1:

输入:

  1
 / \

 3 2
  / \ \

5 3  9

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

 

思路BFS  或者DFS.

已知 node a 的 index i, 子节点的index 为 2*i, 2*i +1

当前节点的宽度为: pos-left +1 ,每层第一个 不为空的, 是最左边,

需要一个 Queue, 然后 建一个数据结构, annotatenode 保留当前节点的深度, 和index.

 1 class Solution {
 2     public int widthOfBinaryTree(TreeNode root) {
 3         Queue<AnnotateNode> queue = new LinkedList<>();
 4         queue.offer(new  AnnotateNode(root,0,0));
 5         int currdepth=0;
 6         int left= 0;
 7         int res =0;
 8         while(!queue.isEmpty()){
 9             AnnotateNode a = queue.poll();
10             if(a.node != null){
11                 
12                 queue.offer(new AnnotateNode(a.node.left,a.depth + 1,a.pos*2));
13                 queue.offer(new AnnotateNode(a.node.right,a.depth + 1,a.pos*2+1));
14                 if(currdepth != a.depth){
15                     currdepth = a.depth;
16                     left = a.pos;
17                 }
18                 System.out.println(a.node.val+"  depth "+ a.depth+ "pos  " +a.pos  +"left "+left);
19                 res = Math.max(res, a.pos - left +1);
20             }
21              
22         }
23        
24         return res;
25     }
26 }
27 
28 class AnnotateNode {
29     TreeNode node;
30     int depth;
31     int pos;
32     public AnnotateNode(TreeNode node,int depth,int pos){
33         this.node = node;
34         this.depth = depth;
35         this.pos = pos;
36     }
37 }