lotus

贵有恒何必三更眠五更起 最无益只怕一日曝十日寒

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
  1846 随笔 :: 0 文章 :: 109 评论 :: 288万 阅读

输出一个二叉树的宽度

思路:二叉树的层序遍历(力扣102)的简单变形,记录下每层的节点个数,取最大值即可。

 

二叉树的层序遍历--打印

public static void level(TreeNode root) {

Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);

while (root != null || !queue.isEmpty()) {
TreeNode node = queue.poll();
System.out.println(node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
}


  

二叉树的层序遍历--带返回值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static List<List<Integer>> level2(TreeNode root) {
    List<List<Integer>> result = new ArrayList<>();
 
    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(root);
 
    while (!queue.isEmpty()) {
        int size = queue.size();
        List<Integer> level = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            TreeNode node = queue.poll();
            level.add(new Integer(node.val));
            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
        }
        result.add(level);
    }
    return result;
}

  

二叉树的层序遍历--最大宽度

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public static Integer getWidth(TreeNode root) {
 
 
    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(root);
 
    Integer maxSize = 0;
 
    while (!queue.isEmpty()) {
        int size = queue.size();
        maxSize = Math.max(maxSize, size);
         
        for (int i = 0; i < size; i++) {
            TreeNode node = queue.poll();
            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
        }
 
    }
    return maxSize;
}

  

posted on   白露~  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2021-04-12 新生代Eden与两个Survivor区的解释
2021-04-12 【todo】堆内存快照phrof文件 使用及分析-动手操作
2021-04-12 MaxTenuringThreshold 和 TargetSurvivorRatio参数说明
点击右上角即可分享
微信分享提示