jayati

Construct Quad Tree

Feb 27th, 2023
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.21 KB | None | 0 0
  1. /*
  2. // Definition for a QuadTree node.
  3. class Node {
  4. public:
  5.     bool val;
  6.     bool isLeaf;
  7.     Node* topLeft;
  8.     Node* topRight;
  9.     Node* bottomLeft;
  10.     Node* bottomRight;
  11.    
  12.     Node() {
  13.         val = false;
  14.         isLeaf = false;
  15.         topLeft = NULL;
  16.         topRight = NULL;
  17.         bottomLeft = NULL;
  18.         bottomRight = NULL;
  19.     }
  20.    
  21.     Node(bool _val, bool _isLeaf) {
  22.         val = _val;
  23.         isLeaf = _isLeaf;
  24.         topLeft = NULL;
  25.         topRight = NULL;
  26.         bottomLeft = NULL;
  27.         bottomRight = NULL;
  28.     }
  29.    
  30.     Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) {
  31.         val = _val;
  32.         isLeaf = _isLeaf;
  33.         topLeft = _topLeft;
  34.         topRight = _topRight;
  35.         bottomLeft = _bottomLeft;
  36.         bottomRight = _bottomRight;
  37.     }
  38. };
  39. */
  40.  
  41. class Solution {
  42. public:
  43.     Node* solve(vector<vector<int>>& grid, int x1, int y1, int length) {
  44.         // Return a leaf node if the matrix size is one.
  45.         if (length == 1) {
  46.             return new Node(grid[x1][y1], true);
  47.         }
  48.        
  49.         // Recursive calls to the four sub-matrices.
  50.         Node* topLeft = solve(grid, x1, y1, length / 2);
  51.         Node* topRight = solve(grid, x1, y1 + length / 2, length / 2);
  52.         Node* bottomLeft = solve(grid, x1 + length / 2, y1, length / 2);
  53.         Node* bottomRight = solve(grid, x1 + length / 2, y1 + length / 2, length / 2);
  54.            
  55.         // If the four returned nodes are leaf and have the same values
  56.         // Return a leaf node with the same value.
  57.         if (topLeft -> isLeaf && topRight -> isLeaf && bottomLeft -> isLeaf && bottomRight -> isLeaf
  58.            && topLeft -> val == topRight -> val && topRight -> val == bottomLeft -> val
  59.            && bottomLeft -> val == bottomRight -> val) {
  60.             return new Node(topLeft -> val, true);
  61.         }
  62.        
  63.         // If the four nodes aren't identical, return non-leaf node with corresponding child pointers.
  64.         return new Node(false, false, topLeft, topRight, bottomLeft, bottomRight);
  65.     }
  66.    
  67.     Node* construct(vector<vector<int>>& grid) {
  68.         return solve(grid, 0, 0, grid.size());
  69.     }
  70. };
Advertisement
Add Comment
Please, Sign In to add comment