zoukankan      html  css  js  c++  java
  • Leetcode 662.二叉树最大宽度

    二叉树最大宽度

    给定一个二叉树,编写一个函数来获取这个树的最大宽度。树的宽度是所有层中的最大宽度。这个二叉树与满二叉树(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.

     1 class Solution {
     2     public int widthOfBinaryTree(TreeNode root) {
     3         Queue<AnnotatedNode> queue = new LinkedList();
     4         queue.add(new AnnotatedNode(root, 0, 0));
     5         int curDepth = 0, left = 0, ans = 0;
     6         while (!queue.isEmpty()) {
     7             AnnotatedNode a = queue.poll();
     8             if (a.node != null) {
     9                 queue.add(new AnnotatedNode(a.node.left, a.depth + 1, a.pos * 2));
    10                 queue.add(new AnnotatedNode(a.node.right, a.depth + 1, a.pos * 2 + 1));
    11                 if (curDepth != a.depth) {
    12                     curDepth = a.depth;
    13                     left = a.pos;
    14                 }
    15                 ans = Math.max(ans, a.pos - left + 1);
    16             }
    17         }
    18         return ans;
    19     }
    20 }
    21 
    22 class AnnotatedNode {
    23     TreeNode node;
    24     int depth, pos;
    25     AnnotatedNode(TreeNode n, int d, int p) {
    26         node = n;
    27         depth = d;
    28         pos = p;
    29     }
    30 }

  • 相关阅读:
    提取RDLC reporting相关dll的方式,打包客户端时需要用
    VS2012程序打包部署详解
    快速打包你的应用程序——Inno Setup
    "RDLC"报表-参数传递及主从报表
    如何在多个页中显示行标题和列标题 (Reporting Services)
    编译cocos2d-x 4.0版本
    2080Ti评测结果
    (转)u3d设计模式
    java基础知识(一)
    Java8新特性学习(一)--lambda表达式
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10394920.html
Copyright © 2011-2022 走看看