题目描述:
给定一个二叉树,编写一个函数来获取这个树的最大宽度。树的宽度是所有层中的最大宽度。这个二叉树与满二叉树(full binary tree)结构相同,但一些节点为空。
每一层的宽度被定义为两个端点(该层最左和最右的非空节点,两端点间的null节点也计入长度)之间的长度。
方法一:
- 按照深度优先的顺序,我们记录每个节点的 pos 。对于每一个深度,第一个到达的位置会被记录在map中。
- 然后对于每一个节点,它对应这一层的可能宽度是 pos - map.get(pos) + 1
- 每次最大的值记录下来即为最大宽度
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
Map<Integer,Integer> map=new HashMap<>();
int res=0;
public int widthOfBinaryTree(TreeNode root) {
func(root,0,0);
return res;
}
void func(TreeNode root,int height,int pos){
if(root!=null){
map.computeIfAbsent(height,value->pos);
res=Math.max(res,pos-map.get(height)+1);
func(root.left,height+1,pos*2);
func(root.right,height+1,pos*2+1);
}
}
}
方法二:
- 将二叉树的下标存储到集合中,根节点下标为 0,左子树结点为 2 * i+1,右子树下标为 2 * i+2。
- 然后进行层次遍历,找出每层的最大宽度
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int widthOfBinaryTree(TreeNode root) {
if(root==null){
return 0;
}
Queue<TreeNode> q=new LinkedList<>();
q.offer(root);
List<Integer> list=new LinkedList<>();
list.add(0);
int max=1;
while(!q.isEmpty()){
int size=q.size();
for(int i=0;i<size;i++){
TreeNode tmp=q.poll();
int node=list.remove(0);
if(tmp.left!=null){
q.offer(tmp.left);
list.add(node*2+1);
}
if(tmp.right!=null){
q.offer(tmp.right);
list.add(node*2+2);
}
}
if(list.size()>=2){
max=Math.max(max,list.get(list.size()-1)-list.get(0)+1);
}
}
return max;
}
}