LeetCode //C++ - 427. Construct Quad Tree

news2024/11/24 4:00:00

427. Construct Quad Tree

Given a n * n matrix grid of 0’s and 1’s only. We want to represent grid with a Quad-Tree.

Return the root of the Quad-Tree representing grid.

A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:

  • val: True if the node represents a grid of 1’s or False if the node represents a grid of 0’s. Notice that you can assign the val to True or False when isLeaf is False, and both are accepted in the answer.
  • isLeaf: True if the node is a leaf node on the tree or False if the node has four children.
class Node {
    public boolean val;
    public boolean isLeaf;
    public Node topLeft;
    public Node topRight;
    public Node bottomLeft;
    public Node bottomRight;
}

We can construct a Quad-Tree from a two-dimensional area using the following steps:

  1. If the current grid has the same value (i.e all 1’s or all 0’s) set isLeaf True and set val to the value of the grid and set the four children to Null and stop.
  2. If the current grid has different values, set isLeaf to False and set val to any value and divide the current grid into four sub-grids as shown in the photo.
  3. Recurse for each of the children with the proper sub-grid.
    在这里插入图片描述
    If you want to know more about the Quad-Tree, you can refer to the wiki.

Quad-Tree format:

You don’t need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal, where null signifies a path terminator where no node exists below.

It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val].

If the value of isLeaf or val is True we represent it as 1 in the list [isLeaf, val] and if the value of isLeaf or val is False we represent it as 0.
 

Example 1:

在这里插入图片描述

Input: grid = [[0,1],[1,0]]
Output: [[0,1],[1,0],[1,1],[1,1],[1,0]]
Explanation: The explanation of this example is shown below:
Notice that 0 represents False and 1 represents True in the photo representing the Quad-Tree.
在这里插入图片描述

Example 2:

在这里插入图片描述

Input: grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]
Output: [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
Explanation: All values in the grid are not the same. We divide the grid into four sub-grids.
The topLeft, bottomLeft and bottomRight each has the same value.
The topRight have different values so we divide it into 4 sub-grids where each has the same value.
Explanation is shown in the photo below:

在这里插入图片描述

Constraints:
  • n == grid.length == grid[i].length
  • n == 2 x 2^x 2x where 0 <= x <= 6

From: LeetCode
Link: 427. Construct Quad Tree


Solution:

Ideas:

1. Node Class:

  • Each node in the tree has a boolean val indicating if it represents a 1 or 0.
  • isLeaf indicates if the node is a leaf node (i.e., it does not have any children and represents a homogenous region in the grid).
  • There are pointers to four potential child nodes: topLeft, topRight, bottomLeft, and bottomRight.

2. Constructing the Quad-Tree:

  • The main function to construct the tree is construct, which is a public method in the Solution class.
  • This method makes use of a recursive helper function, build_tree.

3. Recursive Construction:

  • The build_tree function is the heart of the algorithm. It takes the matrix, coordinates (x and y) of the top-left corner of the current region, and the length (l) of the side of the current region.
  • If the side length (l) is 1, then the region is a single cell, and a leaf node is returned.
  • Otherwise, the function divides the current region into four equal smaller regions (quadrants) and recursively builds quad-trees for each quadrant.
  • After constructing trees for the four quadrants, if all of them are leaf nodes and they have the same value, they are merged into a single leaf node, thus compressing the tree. This is one of the main benefits of the quad-tree representation.
    If they cannot be merged, an internal node with four children is returned.

4. Example:

  • An example 2D grid is provided in the main function to illustrate how to use the Solution class.
Code:
/*
// Definition for a QuadTree node.
class Node {
public:
    bool val;
    bool isLeaf;
    Node* topLeft;
    Node* topRight;
    Node* bottomLeft;
    Node* bottomRight;
    
    Node() {
        val = false;
        isLeaf = false;
        topLeft = NULL;
        topRight = NULL;
        bottomLeft = NULL;
        bottomRight = NULL;
    }
    
    Node(bool _val, bool _isLeaf) {
        val = _val;
        isLeaf = _isLeaf;
        topLeft = NULL;
        topRight = NULL;
        bottomLeft = NULL;
        bottomRight = NULL;
    }
    
    Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) {
        val = _val;
        isLeaf = _isLeaf;
        topLeft = _topLeft;
        topRight = _topRight;
        bottomLeft = _bottomLeft;
        bottomRight = _bottomRight;
    }
};
*/

class Solution {
public:
    Node* construct(vector<vector<int>>& grid) {
        return build_tree(grid, 0, 0, grid.size());
    }

private:
    Node* build_tree(const vector<vector<int>>& matrix, int x, int y, int l) {
        if (l == 1) {
            return new Node(matrix[x][y], true);
        }

        int mid = l / 2;

        Node* topLeft = build_tree(matrix, x, y, mid);
        Node* topRight = build_tree(matrix, x, y + mid, mid);
        Node* bottomLeft = build_tree(matrix, x + mid, y, mid);
        Node* bottomRight = build_tree(matrix, x + mid, y + mid, mid);

        if (topLeft->isLeaf && topRight->isLeaf && bottomLeft->isLeaf && bottomRight->isLeaf &&
            topLeft->val == topRight->val && topLeft->val == bottomLeft->val && topLeft->val == bottomRight->val) {
            bool combinedValue = topLeft->val;
            delete topLeft;
            delete topRight;
            delete bottomLeft;
            delete bottomRight;
            return new Node(combinedValue, true);
        }

        return new Node(false, false, topLeft, topRight, bottomLeft, bottomRight);  // Using false as a dummy value for non-leaf nodes
    }
};

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1100701.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

2023年中国脱硫石膏产量、均价、综合利用量及市场规模分析[图]

脱硫石膏主要成分和天然石膏一样&#xff0c;为二水硫酸钙CaSO42H2O&#xff0c;含量≥93%。脱硫石膏是FGD过程的副产品&#xff0c;FGD过程是一项采用石灰-石灰石回收燃煤或油的烟气中的二氧化硫的技术&#xff0c;其中2022年中国脱硫石膏产量同比增长2.0%&#xff1b;综合利用…

[已解决]llegal target for variable annotation

llegal target for variable annotation 问题 变量注释的非法目标 思路 复制时编码错误&#xff0c;自己敲一遍后正常运行 #** 将垂直知识加入prompt&#xff0c;以使其准确回答 **# prompt_templates { # "recommand":"用户说&#xff1a;__INPUT__ …

上抖音热搜榜需要做哪些准备?

要想在抖音上获得高曝光&#xff0c;首先需要了解抖音热搜榜的算法和规则。抖音热搜榜的排名主要取决于作品的点赞数、评论数、分享数和播放量。其中&#xff0c;播放量是影响排名的关键因素。因此&#xff0c;在创作作品时&#xff0c;要注重提高作品的播放量。此外&#xff0…

最新JustMedia V2.7.3主题破解版去授权WordPress主题模板

JustMedia主题是一款针对有图片或者视频发布需求的网站量身定制开发的wordpress主题&#xff0c;适合各类图片展示类网站使用。 同时JustMedia主题首次加入了我们WPCOM团队独立自主开发的前端用户中心模块&#xff0c;相比用户中心插件可提供更好的体验效果。 新版用户中心为…

麒麟kylinOS 2303通过模板设置电源

原文链接&#xff1a;麒麟kylinOS 2303上通过模板设置电源 hello&#xff0c;大家好啊&#xff0c;今天给大家带来一篇在麒麟kylinOS 2303上通过模板设置电源的文章&#xff0c;主要通过开机启动脚本实现&#xff0c;开机脚本内容主要为gsettings的设置&#xff0c;关于gestati…

超简单小白攻略:如何利用黑群晖虚拟机和内网穿透实现公网访问

文章目录 前言本教程解决的问题是&#xff1a;按照本教程方法操作后&#xff0c;达到的效果是前排提醒&#xff1a; 1. 搭建群晖虚拟机1.1 下载黑群晖文件vmvare虚拟机安装包1.2 安装VMware虚拟机&#xff1a;1.3 解压黑群晖虚拟机文件1.4 虚拟机初始化1.5 没有搜索到黑群晖的解…

在 GeoServer 上发布 Shapefile 文件作为 WMS 数据

首先需要有 java 环境:https://zhuhukang.blog.csdn.net/article/details/132814744 1. 数据发布 点击数据存储,添加存储Shapefile 文件数据源添加 新建矢量数据源 点击保存,然后跳转下个页面进行发布 查找选择4326,然后从数据中进行计算 查看

SpringBoot整合Activiti7——执行监听器(六)

文章目录 一、执行监听器事件类型生命周期配置方式(选)代码实现xml文件创建监听器class方法expression方法delegateExpression 测试流程部署流程启动流程完成任务 一、执行监听器 在流程实例执行过程中触发某个事件时&#xff0c;Activiti提供的执行监听器可以捕获该事件并执行…

AI原生应用速通指南

作者 | 百度文库APP 导读 百度创始人、董事长兼首席执行官李彦宏早在今年年初所预测的&#xff1a;大模型时代最大的机会在于应用层&#xff0c;会出现“杀手级”应用。 全文4448字&#xff0c;预计阅读时间12分钟。 前言 “我们要让AI走下技术的“神坛”&#xff0c;深入应用的…

强化学习与视觉语言模型之间的碰撞,UC伯克利提出语言奖励调节LAMP框架

文章链接&#xff1a; https://arxiv.org/abs/2308.12270 代码仓库&#xff1a; https://github.com/ademiadeniji/lamp 在强化学习&#xff08;RL&#xff09;领域&#xff0c;一个重要的研究方向是如何巧妙的设计模型的奖励机制&#xff0c;传统的方式是设计手工奖励函数&…

微信小程序修改van-popup的背景颜色

效果图&#xff1a; van-popup背景颜色渐变 使用深度修改样式不生效&#xff0c;直接在 custom-style里面修改即可&#xff1b; <van-popup position"bottom"custom-style"height:25%;background:linear-gradient(95deg, #F8FCFF -0.03%, #EDF5FF 64.44…

JIRA 在 2024 年完全停止服务器版本支持

在服务器上的开源许可证版本已经要过期了&#xff0c;想去更新下。 发现&#xff0c;JIRA 的所有服务器版本的支持马上就要结束了。 这就意味着&#xff0c;如果你部署的服务器版本的 JIRA 的话&#xff0c;你将没有办法对服务器进行更新。 貌似&#xff0c;必须使用 JIRA 提供…

用建筑中智能消防应急照明系统的应用

【摘要】&#xff1a;火灾应急照明是火灾安全疏散、保障消防人员生命安全的关键。对电气设计人员来说&#xff0c;火灾紧急照明系统的设计非常必要&#xff0c;消防紧急照明系统启动与其正常工作状态有直接的关系&#xff0c;但由于其存在的问题通常不能被及时发现&#xff0c;…

苏轼的人生足迹

传说徐霞客游历了中国所有角落&#xff0c;但实际上北宋才子苏东坡也同样历经千辛万苦&#xff0c;漫游天涯海角。这两者的不同之处在于&#xff0c;徐霞客是为了旅游而旅游&#xff0c;而苏东坡的大部分旅程则是由于他的贬谪之事导致的。 苏东坡一生到过很多地方&#xff0c;…

如何打造智能公厕:实现智慧监测、自动化运营和智慧化管理

在现代城市里&#xff0c;公共厕所是人们不可或缺的基础设施之一。然而&#xff0c;传统的公厕管理方式已经无法满足人们对公厕的期望&#xff0c;因此需要采用智慧公厕管理系统来提升公厕服务的质量。本文将以智慧公厕领先厂家广州中期科技有限公司&#xff0c;大量精品案例现…

实验笔记之——可见光通信调制驱动芯片模组

本博文记录本团队研发出的VLC驱动调制芯片模组&#xff08;如下图所示&#xff09;的驱动调制代码烧录过程。 实物模组正面 实物模组反面 首先需要安装keil5&#xff0c;其安装与编译过程请参考博客&#xff1a;实验笔记之——单片机烧录的实验过程_烧录程序的基本步骤-CSDN博客…

ES6(ECMAScript 2015)有哪些新属性,如何判断当前浏览器是否支持?

ES6&#xff08;ECMAScript 2015&#xff09;引入了许多新的语法和特性&#xff0c;以增强 JavaScript 编程语言的功能。以下是一些常见的 ES6 语法和特性以及它们的解释&#xff1a; let 和 const 声明&#xff1a; let 和 const 用于声明变量&#xff0c;代替了旧的 var 关键…

什么是关系数据库,你知道吗?

什么是关系数据库管理系统 关系数据库管理系统&#xff08;RDBMS&#xff0c;relational database management system&#xff09;是基于关系数据模型的数字数据库&#xff0c;由 E. F. Codd 于 1970 年提出。 许多关系数据库都提供使用结构化查询语言 SQL&#xff08;Struct…

6、函数式编程--高级用法

目录 7. 高级用法基本数据类型优化并行流parallel()parallelStream() 7. 高级用法 基本数据类型优化 ​ 我们之前用到的很多Stream的方法由于都使用了泛型。所以涉及到的参数和返回值都是引用数据类型。 ​ 即使我们操作的是整数小数&#xff0c;但是实际用的都是他们的包装…

【触想智能】工业级触摸显示器的分类与应用分享

工业级触摸显示器是具有触摸功能的工业显示器&#xff0c;常见的触摸方式有电容触摸和电阻触摸。它是应用在工业上的设备&#xff0c;和普通的显示器有着很大的区别。 工业级触摸显示器由液晶触摸屏、功能主板、外壳三部分组成&#xff0c;结构用料一般都采用铝合金材质&#x…