problem:https://leetcode.com/problems/construct-quad-tree/
一道简单的建树题目,模拟即可。
/* // 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 { public: bool IsLeaf(vector<vector<int>>& grid, int x0, int y0, int x1, int y1) { int last = grid[x0][y0]; for(int i = x0; i <= x1; i++) { for(int j = y0; j <= y1; j++) { if(grid[i][j] != last) { return false; } } } return true; } Node* construct(vector<vector<int>>& grid, int x0, int y0, int x1, int y1) { if(IsLeaf(grid, x0, y0, x1, y1)) { Node* node = new Node(grid[x0][y0], true,nullptr,nullptr,nullptr,nullptr); return node; } Node* node = new Node(); node->isLeaf = false; node->val = ‘*‘; int mx = (x0 + x1) / 2; int my = (y0 + y1) / 2; vector<int> cx0 { x0, x0 ,mx + 1, mx + 1 }; vector<int> cy0 { y0, my + 1,y0 ,my + 1 }; vector<int> cx1 { mx, mx ,x1 ,x1 }; vector<int> cy1 { my, y1 ,my ,y1 }; vector<Node**> curNode { &node->topLeft, &node->topRight, &node->bottomLeft, &node->bottomRight }; for(int k = 0; k < 4; k++) { *(curNode[k]) = construct(grid, cx0[k], cy0[k], cx1[k], cy1[k]); } return node; } Node* construct(vector<vector<int>>& grid) { return construct(grid, 0, 0, grid.size() - 1, grid[0].size() - 1); } };
[树] leetcode 427 Construct Quad Tree
原文:https://www.cnblogs.com/fish1996/p/11295861.html