• 【二叉树】二叉树最大宽度


    题目描述

    给你一棵二叉树的根节点 root ,返回树的 最大宽度 。

    树的 最大宽度 是所有层中最大的 宽度 。

    每一层的 宽度 被定义为该层最左和最右的非空节点(即,两个端点)之间的长度。将这个二叉树视作与满二叉树结构相同,两端点间会出现一些延伸到这一层的 null 节点,这些 null 节点也计入长度。

    示例1:

    输入:root = [11,12,13,null,14]
    输出:2
    解释:最大宽度出现在树的第 2 层,宽度为 2 (12,13) 。

    解题思路 

    这道题其实是利用二叉树的性质,每一层的下标规则:左子树下标=父节点下标*2;右子树下标=父节点下标*2+1;如下图所示:

    这里在原来树结构的基础上,增进position,用于记录每个节点的下标,整个类如下:

    TreeNode

    package org.example;
    
    public class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;
    
        public TreeNode() {
        }
    
        public TreeNode(int val) {
            this.val = val;
        }
    
        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    TreeNodeExtend

     

    class TreeNodeExtend {
    
        TreeNode node;
        int position;
    
        public TreeNodeExtend(TreeNode node, int position) {
            this.node = node;
            this.position = position;
        }
    }

     

    接着使用BFS进行遍历,这里我使用LinkedList模拟队列操作,具体代码实现如下:

    1. import org.example.TreeNode;
    2. import java.util.LinkedList;
    3. class Solution {
    4. public int widthOfBinaryTree(TreeNode root) {
    5. if (root == null) {
    6. return 0;
    7. }
    8. LinkedList deque = new LinkedList<>();
    9. deque.offer(new TreeNodeExtend(root, 0));
    10. int max = 1;
    11. while (!deque.isEmpty()) {
    12. max = Math.max(max, deque.get(deque.size() - 1).position - deque.get(0).position + 1);
    13. int sz = deque.size();
    14. for (int i = 0; i < sz; i++) {
    15. TreeNodeExtend node = deque.poll();
    16. if (node.node.left != null) {
    17. deque.offer(new TreeNodeExtend(node.node.left, node.position * 2));
    18. }
    19. if (node.node.right != null) {
    20. deque.offer(new TreeNodeExtend(node.node.right, node.position * 2 + 1));
    21. }
    22. }
    23. }
    24. return max;
    25. }
    26. class TreeNodeExtend {
    27. TreeNode node;
    28. int position;
    29. public TreeNodeExtend(TreeNode node, int position) {
    30. this.node = node;
    31. this.position = position;
    32. }
    33. }
    34. }

     

    总结

    这道题就是2-3个简单问题组合到一起的中等难度问题;核心问题有:

    1. 二叉树的层序遍历,BFS;
    2. 二叉树的性质-下标生成的规则,并且构造有下标的二叉树;
    3. 最大值的获取。

    这道题按照上述解法,耗时1ms左右。如果有更高效、更简洁的思路欢迎回复。

  • 相关阅读:
    C# 通过ARP技术来观察目标主机数据包
    【面试题】Vue中的$router 和 $route的区别
    前端面试(4)—— DOM事件的总结
    深度学习入门(5) - RNN
    C++核心编程——5 文件操作
    基于动态自适应加权极限RUL 预测(Matlab代码实现)
    mysql 查询
    xv6第一章:Operating system interfaces
    大厂面试 | 百度Java面试题分享
    css 10-13
  • 原文地址:https://blog.csdn.net/weiliuhong1/article/details/126554134