【Leetcode】427. Construct Quad Tree

题目地址:

https://leetcode.com/problems/construct-quad-tree/

给定一个 n × n n\times n n×n 01 01 01方阵,构造四叉树。构造过程是递归的,每个节点有四个孩子,分别代表该节点所表示的方阵的左上、右上、左下和右下区块。如果该区块的值都相同,则该节点的值为这个相同值,四个孩子设为null;否则继续细分。如果该节点所表示的方阵只有一个元素,则其为叶子。其节点定义如下:

class Node {
public:
    bool val;
    bool isLeaf;
    Node* topLeft;
    Node* topRight;
    Node* bottomLeft;
    Node* bottomRight;
    
    Node() {
        val = false;
        isLeaf = false;
        topLeft = NULL;
        topRight = NULL;
        bottomLeft = NULL;
        bottomRight = NULL;
    }
    
    Node(bool _val, bool _isLeaf) {
        val = _val;
        isLeaf = _isLeaf;
        topLeft = NULL;
        topRight = NULL;
        bottomLeft = NULL;
        bottomRight = NULL;
    }
    
    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:
  vector<vector<int>> pre;
  Node* construct(vector<vector<int>>& g) {
    int n = g.size();
    pre = vector<vector<int>>(n + 1, vector<int>(n + 1, 0));
    for (int i = 0; i < n; i++)
      for (int j = 0; j < n; j++)
        pre[i + 1][j + 1] = g[i][j] + pre[i + 1][j] + pre[i][j + 1] - pre[i][j];
    return dfs(0, 0, n - 1, n - 1);
  }

  Node* dfs(int x1, int y1, int x2, int y2) {
    int sum =
        pre[x2 + 1][y2 + 1] - pre[x2 + 1][y1] - pre[x1][y2 + 1] + pre[x1][y1];
    int n = x2 - x1 + 1;
    if (!sum || sum == n * n)
      return new Node(!!sum, true, nullptr, nullptr, nullptr, nullptr);
    Node* topLeft = dfs(x1, y1, (x1 + x2) / 2, (y1 + y2) / 2);
    Node* topRight = dfs(x1, (y1 + y2) / 2 + 1, (x1 + x2) / 2, y2);
    Node* bottomLeft = dfs((x1 + x2) / 2 + 1, y1, x2, (y1 + y2) / 2);
    Node* bottomRight = dfs((x1 + x2) / 2 + 1, (y1 + y2) / 2 + 1, x2, y2);
    return new Node(1, false, topLeft, topRight, bottomLeft, bottomRight);
  }
};

时空复杂度 O ( n 2 ) O(n^2) O(n2)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值