{ "data": { "question": { "questionId": "772", "questionFrontendId": "427", "boundTopicId": null, "title": "Construct Quad Tree", "titleSlug": "construct-quad-tree", "content": "

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

\n\n

Return the root of the Quad-Tree representing the grid.

\n\n

Notice that you can assign the value of a node to True or False when isLeaf is False, and both are accepted in the answer.

\n\n

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

\n\n\n\n
\nclass Node {\n    public boolean val;\n    public boolean isLeaf;\n    public Node topLeft;\n    public Node topRight;\n    public Node bottomLeft;\n    public Node bottomRight;\n}
\n\n

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

\n\n
    \n\t
  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. \n\t
  3. 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.
  4. \n\t
  5. Recurse for each of the children with the proper sub-grid.
  6. \n
\n\"\"\n

If you want to know more about the Quad-Tree, you can refer to the wiki.

\n\n

Quad-Tree format:

\n\n

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.

\n\n

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].

\n\n

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.

\n\n

 

\n

Example 1:

\n\"\"\n
\nInput: grid = [[0,1],[1,0]]\nOutput: [[0,1],[1,0],[1,1],[1,1],[1,0]]\nExplanation: The explanation of this example is shown below:\nNotice that 0 represnts False and 1 represents True in the photo representing the Quad-Tree.\n\"\"\n
\n\n

Example 2:

\n\n

\"\"

\n\n
\nInput: 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]]\nOutput: [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]\nExplanation: All values in the grid are not the same. We divide the grid into four sub-grids.\nThe topLeft, bottomLeft and bottomRight each has the same value.\nThe topRight have different values so we divide it into 4 sub-grids where each has the same value.\nExplanation is shown in the photo below:\n\"\"\n
\n\n

 

\n

Constraints:

\n\n\n", "translatedTitle": null, "translatedContent": null, "isPaidOnly": false, "difficulty": "Medium", "likes": 482, "dislikes": 678, "isLiked": null, "similarQuestions": "[]", "exampleTestcases": "[[0,1],[1,0]]\n[[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]]", "categoryTitle": "Algorithms", "contributors": [], "topicTags": [ { "name": "Array", "slug": "array", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Divide and Conquer", "slug": "divide-and-conquer", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Tree", "slug": "tree", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Matrix", "slug": "matrix", "translatedName": null, "__typename": "TopicTagNode" } ], "companyTagStats": null, "codeSnippets": [ { "lang": "C++", "langSlug": "cpp", "code": "/*\n// Definition for a QuadTree node.\nclass Node {\npublic:\n bool val;\n bool isLeaf;\n Node* topLeft;\n Node* topRight;\n Node* bottomLeft;\n Node* bottomRight;\n \n Node() {\n val = false;\n isLeaf = false;\n topLeft = NULL;\n topRight = NULL;\n bottomLeft = NULL;\n bottomRight = NULL;\n }\n \n Node(bool _val, bool _isLeaf) {\n val = _val;\n isLeaf = _isLeaf;\n topLeft = NULL;\n topRight = NULL;\n bottomLeft = NULL;\n bottomRight = NULL;\n }\n \n Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) {\n val = _val;\n isLeaf = _isLeaf;\n topLeft = _topLeft;\n topRight = _topRight;\n bottomLeft = _bottomLeft;\n bottomRight = _bottomRight;\n }\n};\n*/\n\nclass Solution {\npublic:\n Node* construct(vector>& grid) {\n \n }\n};", "__typename": "CodeSnippetNode" }, { "lang": "Java", "langSlug": "java", "code": "/*\n// Definition for a QuadTree node.\nclass Node {\n public boolean val;\n public boolean isLeaf;\n public Node topLeft;\n public Node topRight;\n public Node bottomLeft;\n public Node bottomRight;\n\n \n public Node() {\n this.val = false;\n this.isLeaf = false;\n this.topLeft = null;\n this.topRight = null;\n this.bottomLeft = null;\n this.bottomRight = null;\n }\n \n public Node(boolean val, boolean isLeaf) {\n this.val = val;\n this.isLeaf = isLeaf;\n this.topLeft = null;\n this.topRight = null;\n this.bottomLeft = null;\n this.bottomRight = null;\n }\n \n public Node(boolean val, boolean isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bottomRight) {\n this.val = val;\n this.isLeaf = isLeaf;\n this.topLeft = topLeft;\n this.topRight = topRight;\n this.bottomLeft = bottomLeft;\n this.bottomRight = bottomRight;\n }\n};\n*/\n\nclass Solution {\n public Node construct(int[][] grid) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Python", "langSlug": "python", "code": "\"\"\"\n# Definition for a QuadTree node.\nclass Node(object):\n def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):\n self.val = val\n self.isLeaf = isLeaf\n self.topLeft = topLeft\n self.topRight = topRight\n self.bottomLeft = bottomLeft\n self.bottomRight = bottomRight\n\"\"\"\n\nclass Solution(object):\n def construct(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: Node\n \"\"\"\n ", "__typename": "CodeSnippetNode" }, { "lang": "Python3", "langSlug": "python3", "code": "\"\"\"\n# Definition for a QuadTree node.\nclass Node:\n def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):\n self.val = val\n self.isLeaf = isLeaf\n self.topLeft = topLeft\n self.topRight = topRight\n self.bottomLeft = bottomLeft\n self.bottomRight = bottomRight\n\"\"\"\n\nclass Solution:\n def construct(self, grid: List[List[int]]) -> 'Node':\n ", "__typename": "CodeSnippetNode" }, { "lang": "C#", "langSlug": "csharp", "code": "/*\n// Definition for a QuadTree node.\npublic class Node {\n public bool val;\n public bool isLeaf;\n public Node topLeft;\n public Node topRight;\n public Node bottomLeft;\n public Node bottomRight;\n\n public Node() {\n val = false;\n isLeaf = false;\n topLeft = null;\n topRight = null;\n bottomLeft = null;\n bottomRight = null;\n }\n \n public Node(bool _val, bool _isLeaf) {\n val = _val;\n isLeaf = _isLeaf;\n topLeft = null;\n topRight = null;\n bottomLeft = null;\n bottomRight = null;\n }\n \n public Node(bool _val,bool _isLeaf,Node _topLeft,Node _topRight,Node _bottomLeft,Node _bottomRight) {\n val = _val;\n isLeaf = _isLeaf;\n topLeft = _topLeft;\n topRight = _topRight;\n bottomLeft = _bottomLeft;\n bottomRight = _bottomRight;\n }\n}\n*/\n\npublic class Solution {\n public Node Construct(int[][] grid) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "JavaScript", "langSlug": "javascript", "code": "/**\n * // Definition for a QuadTree node.\n * function Node(val,isLeaf,topLeft,topRight,bottomLeft,bottomRight) {\n * this.val = val;\n * this.isLeaf = isLeaf;\n * this.topLeft = topLeft;\n * this.topRight = topRight;\n * this.bottomLeft = bottomLeft;\n * this.bottomRight = bottomRight;\n * };\n */\n\n/**\n * @param {number[][]} grid\n * @return {Node}\n */\nvar construct = function(grid) {\n \n};", "__typename": "CodeSnippetNode" }, { "lang": "Ruby", "langSlug": "ruby", "code": "# Definition for a QuadTree node.\n# class Node\n# attr_accessor :val, :isLeaf, :topLeft, :topRight, :bottomLeft, :bottomRight\n# def initialize(val=false, isLeaf=false, topLeft=nil, topRight=nil, bottomLeft=nil, bottomRight=nil)\n# @val = val\n# @isLeaf = isLeaf\n# @topLeft = topLeft\n# @topRight = topRight\n# @bottomLeft = bottomLeft\n# @bottomRight = bottomRight\n# end\n# end\n\n# @param {Integer[][]} grid\n# @return {Node}\ndef construct(grid)\n\t\nend", "__typename": "CodeSnippetNode" }, { "lang": "Swift", "langSlug": "swift", "code": "/**\n * Definition for a QuadTree node.\n * public class Node {\n * public var val: Bool\n * public var isLeaf: Bool\n * public var topLeft: Node?\n * public var topRight: Node?\n * public var bottomLeft: Node?\n * public var bottomRight: Node?\n * public init(_ val: Bool, _ isLeaf: Bool) {\n * self.val = val\n * self.isLeaf = isLeaf\n * self.topLeft = nil\n * self.topRight = nil\n * self.bottomLeft = nil\n * self.bottomRight = nil\n * }\n * }\n */\n\nclass Solution {\n func construct(_ grid: [[Int]]) -> Node? {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Go", "langSlug": "golang", "code": "/**\n * Definition for a QuadTree node.\n * type Node struct {\n * Val bool\n * IsLeaf bool\n * TopLeft *Node\n * TopRight *Node\n * BottomLeft *Node\n * BottomRight *Node\n * }\n */\n\nfunc construct(grid [][]int) *Node {\n \n}", "__typename": "CodeSnippetNode" }, { "lang": "Scala", "langSlug": "scala", "code": "/**\n * Definition for a QuadTree node.\n * class Node(var _value: Boolean, var _isLeaf: Boolean) {\n * var value: Int = _value\n * var isLeaf: Boolean = _isLeaf\n * var topLeft: Node = null\n * var topRight: Node = null\n * var bottomLeft: Node = null\n * var bottomRight: Node = null\n * }\n */\n\nobject Solution {\n def construct(grid: Array[Array[Int]]): Node = {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Kotlin", "langSlug": "kotlin", "code": "/**\n * Definition for a QuadTree node.\n * class Node(var `val`: Boolean, var isLeaf: Boolean) {\n * var topLeft: Node? = null\n * var topRight: Node? = null\n * var bottomLeft: Node? = null\n * var bottomRight: Node? = null\n * }\n */\n\nclass Solution {\n fun construct(grid: Array): Node? {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "PHP", "langSlug": "php", "code": "/**\n * Definition for a QuadTree node.\n * class Node {\n * public $val = null;\n * public $isLeaf = null;\n * public $topLeft = null;\n * public $topRight = null;\n * public $bottomLeft = null;\n * public $bottomRight = null;\n * function __construct($val, $isLeaf) {\n * $this->val = $val;\n * $this->isLeaf = $isLeaf;\n * $this->topLeft = null;\n * $this->topRight = null;\n * $this->bottomLeft = null;\n * $this->bottomRight = null;\n * }\n * }\n */\n\nclass Solution {\n /**\n * @param Integer[][] $grid\n * @return Node\n */\n function construct($grid) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "TypeScript", "langSlug": "typescript", "code": "/**\n * Definition for node.\n * class Node {\n * val: boolean\n * isLeaf: boolean\n * topLeft: Node | null\n * topRight: Node | null\n * bottomLeft: Node | null\n * bottomRight: Node | null\n * constructor(val?: boolean, isLeaf?: boolean, topLeft?: Node, topRight?: Node, bottomLeft?: Node, bottomRight?: Node) {\n * this.val = (val===undefined ? false : val)\n * this.isLeaf = (isLeaf===undefined ? false : isLeaf)\n * this.topLeft = (topLeft===undefined ? null : topLeft)\n * this.topRight = (topRight===undefined ? null : topRight)\n * this.bottomLeft = (bottomLeft===undefined ? null : bottomLeft)\n * this.bottomRight = (bottomRight===undefined ? null : bottomRight)\n * }\n * }\n */\n\nfunction construct(grid: number[][]): Node | null {\n\n};", "__typename": "CodeSnippetNode" } ], "stats": "{\"totalAccepted\": \"41.5K\", \"totalSubmission\": \"63.7K\", \"totalAcceptedRaw\": 41544, \"totalSubmissionRaw\": 63663, \"acRate\": \"65.3%\"}", "hints": [], "solution": null, "status": null, "sampleTestCase": "[[0,1],[1,0]]", "metaData": "{\n \"name\": \"construct\",\n \"params\": [\n {\n \"name\": \"grid\",\n \"type\": \"integer[][]\"\n }\n ],\n \"return\": {\n \"type\": \"list>\"\n },\n \"languages\": [\n \"cpp\",\n \"java\",\n \"python\",\n \"csharp\",\n \"javascript\",\n \"python3\",\n \"kotlin\",\n \"ruby\",\n \"scala\",\n \"swift\",\n \"golang\",\n \"php\",\n \"typescript\"\n ],\n \"manual\": true\n}", "judgerAvailable": true, "judgeType": "large", "mysqlSchemas": [], "enableRunCode": true, "enableTestMode": false, "enableDebugger": true, "envInfo": "{\"cpp\": [\"C++\", \"

Compiled with clang 11 using the latest C++ 17 standard.

\\r\\n\\r\\n

Your code is compiled with level two optimization (-O2). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\"], \"java\": [\"Java\", \"

OpenJDK 17 . Java 8 features such as lambda expressions and stream API can be used.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\\r\\n

Includes Pair class from https://docs.oracle.com/javase/8/javafx/api/javafx/util/Pair.html.

\"], \"python\": [\"Python\", \"

Python 2.7.12.

\\r\\n\\r\\n

Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.

\\r\\n\\r\\n

For Map/TreeMap data structure, you may use sortedcontainers library.

\\r\\n\\r\\n

Note that Python 2.7 will not be maintained past 2020. For the latest Python, please choose Python3 instead.

\"], \"csharp\": [\"C#\", \"

C# 10 with .NET 6 runtime

\\r\\n\\r\\n

Your code is compiled with debug flag enabled (/debug).

\"], \"javascript\": [\"JavaScript\", \"

Node.js 16.13.2.

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES6 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\\r\\n\\r\\n

For Priority Queue / Queue data structures, you may use datastructures-js/priority-queue and datastructures-js/queue.

\"], \"ruby\": [\"Ruby\", \"

Ruby 3.1

\\r\\n\\r\\n

Some common data structure implementations are provided in the Algorithms module: https://www.rubydoc.info/github/kanwei/algorithms/Algorithms

\"], \"swift\": [\"Swift\", \"

Swift 5.5.2.

\"], \"golang\": [\"Go\", \"

Go 1.17.6.

\\r\\n\\r\\n

Support https://godoc.org/github.com/emirpasic/gods library.

\"], \"python3\": [\"Python3\", \"

Python 3.10.

\\r\\n\\r\\n

Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.

\\r\\n\\r\\n

For Map/TreeMap data structure, you may use sortedcontainers library.

\"], \"scala\": [\"Scala\", \"

Scala 2.13.7.

\"], \"kotlin\": [\"Kotlin\", \"

Kotlin 1.3.10.

\"], \"php\": [\"PHP\", \"

PHP 8.1.

\\r\\n

With bcmath module

\"], \"typescript\": [\"Typescript\", \"

TypeScript 4.5.4, Node.js 16.13.2.

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES2020 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }