leetcode 427. Construct Quad Tree | 427. 建立四叉树(分治法)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 427. Construct Quad Tree | 427. 建立四叉树(分治法)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
https://leetcode.com/problems/construct-quad-tree/
題解
/* // Definition for a QuadTree node. class Node {public boolean val;public boolean isLeaf;public Node topLeft;public Node topRight;public Node bottomLeft;public Node bottomRight;public Node() {this.val = false;this.isLeaf = false;this.topLeft = null;this.topRight = null;this.bottomLeft = null;this.bottomRight = null;}public Node(boolean val, boolean isLeaf) {this.val = val;this.isLeaf = isLeaf;this.topLeft = null;this.topRight = null;this.bottomLeft = null;this.bottomRight = null;}public Node(boolean val, boolean isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bottomRight) {this.val = val;this.isLeaf = isLeaf;this.topLeft = topLeft;this.topRight = topRight;this.bottomLeft = bottomLeft;this.bottomRight = bottomRight;} }; */class Solution {public Node construct(int[][] grid) {// x,y,size確定一個正方形Node root = partition(grid, 0, 0, grid.length);return root;}// 通過4個val判斷是否有相異元素public Node partition(int[][] grid, int x, int y, int size) {Node node = new Node();if (size == 1) {node.isLeaf = true;node.val = (grid[x][y] == 1);return node;}Node TL = partition(grid, x, y, size / 2);Node TR = partition(grid, x, y + size / 2, size / 2);Node BL = partition(grid, x + size / 2, y, size / 2);Node BR = partition(grid, x + size / 2, y + size / 2, size / 2);if (TL.isLeaf && TR.isLeaf && BL.isLeaf && BR.isLeaf && TL.val == TR.val && TR.val == BL.val && BL.val == BR.val) { // 四葉子合并node.isLeaf = true;node.val = TL.val;} else { // 四葉子無法合并node.isLeaf = false;node.topLeft = TL;node.topRight = TR;node.bottomLeft = BL;node.bottomRight = BR;}return node;} }總結
以上是生活随笔為你收集整理的leetcode 427. Construct Quad Tree | 427. 建立四叉树(分治法)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 423. Recons
- 下一篇: 430. Flatten a Multi