LeetCode 427. 建立四叉树(递归)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 427. 建立四叉树(递归)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 題目
我們想要使用一棵四叉樹來儲存一個 N x N 的布爾值網絡。網絡中每一格的值只會是真或假。樹的根結點代表整個網絡。對于每個結點, 它將被分等成四個孩子結點直到這個區域內的值都是相同的.
每個結點還有另外兩個布爾變量: isLeaf 和 val。isLeaf 當這個節點是一個葉子結點時為真。val 變量儲存葉子結點所代表的區域的值。
你的任務是使用一個四叉樹表示給定的網絡。下面的例子將有助于你理解這個問題:
給定下面這個8 x 8 網絡,我們將這樣建立一個對應的四叉樹:
由上文的定義,它能被這樣分割:
對應的四叉樹應該像下面這樣,每個結點由一對 (isLeaf, val) 所代表.
對于非葉子結點,val 可以是任意的,所以使用 * 代替。
提示:
N 將小于 1000 且確保是 2 的整次冪。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/construct-quad-tree
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 遞歸建樹
// Definition for a QuadTree node. class Node { public:bool val;bool isLeaf;Node* topLeft;Node* topRight;Node* bottomLeft;Node* bottomRight;Node() {}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 {Node* r; public:Node* construct(vector<vector<int>>& grid) {int m = grid.size();r = build(grid,0,0,m-1,m-1);return r;}Node* build(vector<vector<int>>& grid, int sx, int sy, int ex, int ey) {if(sx == ex || sy == ey)//只有1個單元了,不能劃分了return new Node(grid[sx][sy],true,0,0,0,0);int mx = (sx+ex)/2, my = (sy+ey)/2;Node *root = new Node(true,true,0,0,0,0);//默認是葉子節點,val值是1int b1, b2, b3, b4;//是全1?全0?兩種都有?b1 = judge(grid,sx,sy,mx,my);b2 = judge(grid,sx,my+1,mx,ey);b3 = judge(grid,mx+1,sy,ex,my);b4 = judge(grid,mx+1,my+1,ex,ey);if(b1==1 && b2==1 && b3==1 && b4==1){ //全1return root;}else if(b1==0 && b2==0 && b3==0 && b4==0){ //全0root->val = false;return root;}else{ //0,1都有root->isLeaf = false;root->topLeft = build(grid,sx,sy,mx,my);root->topRight = build(grid,sx,my+1,mx,ey);root->bottomLeft = build(grid,mx+1,sy,ex,my);root->bottomRight = build(grid,mx+1,my+1,ex,ey);return root;}}int judge(vector<vector<int>>& grid, int sx, int sy, int ex, int ey){int i, j;bool allone = 1, allzero = 1;for(i = sx; i <= ex; ++i)for(j = sy; j <= ey; ++j)if(grid[i][j] == 0){allone = false;}else{allzero = false;}if(allone^allzero)//全0或者全1{if(allone)return 1;//全1if(allzero)return 0;//全0}return -1;//0,1都有} };總結
以上是生活随笔為你收集整理的LeetCode 427. 建立四叉树(递归)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 程序员面试金典 - 面试题 02.03.
- 下一篇: LeetCode 1289. 下降路径最