|
| 1 | +/** |
| 2 | + * 427. Construct Quad Tree |
| 3 | + * https://leetcode.com/problems/construct-quad-tree/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given a n * n matrix grid of 0's and 1's only. We want to represent grid with a Quad-Tree. |
| 7 | + * |
| 8 | + * Return the root of the Quad-Tree representing grid. |
| 9 | + * |
| 10 | + * A Quad-Tree is a tree data structure in which each internal node has exactly four children. |
| 11 | + * Besides, each node has two attributes: |
| 12 | + * - val: True if the node represents a grid of 1's or False if the node represents a grid of |
| 13 | + * 0's. Notice that you can assign the val to True or False when isLeaf is False, and both are |
| 14 | + * accepted in the answer. |
| 15 | + * - isLeaf: True if the node is a leaf node on the tree or False if the node has four children. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * // Definition for a QuadTree node. |
| 20 | + * function _Node(val,isLeaf,topLeft,topRight,bottomLeft,bottomRight) { |
| 21 | + * this.val = val; |
| 22 | + * this.isLeaf = isLeaf; |
| 23 | + * this.topLeft = topLeft; |
| 24 | + * this.topRight = topRight; |
| 25 | + * this.bottomLeft = bottomLeft; |
| 26 | + * this.bottomRight = bottomRight; |
| 27 | + * }; |
| 28 | + */ |
| 29 | + |
| 30 | +/** |
| 31 | + * @param {number[][]} grid |
| 32 | + * @return {_Node} |
| 33 | + */ |
| 34 | +var construct = function(grid) { |
| 35 | + return build(0, 0, grid.length); |
| 36 | + |
| 37 | + function build(x, y, n) { |
| 38 | + const value = grid[x][y]; |
| 39 | + for (let i = x; i < x + n; i++) { |
| 40 | + for (let j = y; j < y + n; j++) { |
| 41 | + if (grid[i][j] !== value) { |
| 42 | + n /= 2; |
| 43 | + return new _Node(true, false, |
| 44 | + build(x, y, n), |
| 45 | + build(x, y + n, n), |
| 46 | + build(x + n, y, n), |
| 47 | + build(x + n, y + n, n) |
| 48 | + ); |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + return new _Node(value === 1, true, null, null, null, null); |
| 53 | + } |
| 54 | +}; |
0 commit comments