LeetCode427. Construct Quad Tree

We want to use quad trees to store an N x N boolean grid. Each cell in the grid can only be true or false. The root node represents the whole grid. For each node, it will be subdivided into four children nodes until the values in the region it represents are all the same.

Each node has another two boolean attributes : isLeaf and valisLeaf is true if and only if the node is a leaf node. The val attribute for a leaf node contains the value of the region it represents.

Your task is to use a quad tree to represent a given grid. The following example may help you understand the problem better:

Given the 8 x 8 grid below, we want to construct the corresponding quad tree:

It can be divided according to the definition above:

 

The corresponding quad tree should be as following, where each node is represented as a (isLeaf, val) pair.

For the non-leaf nodes, val can be arbitrary, so it is represented as *.

Note:

  1. N is less than 1000 and guaranteened to be a power of 2.
  2. If you want to know more about the quad tree, you can refer to its wiki.

参考资料:here

/*
// 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 {
private:
	vector<vector<int>> _grid;
	Node* dfs(int x, int y, int len) {
		if (len == 1)
			return new Node(_grid[x][y], true, NULL, NULL, NULL, NULL);
		len /= 2;
		Node* top_left = dfs(x, y, len);
		Node* top_right = dfs(x, y + len, len);
		Node* bottom_left = dfs(x + len, y, len);
		Node* bottom_right = dfs(x + len, y + len, len);
		
		bool all_leaf = top_left->isLeaf && top_right->isLeaf && bottom_left->isLeaf && bottom_right->isLeaf;
		bool all_same = (top_left->val == top_right->val) && (top_right->val == bottom_left->val) && (bottom_left->val == bottom_right->val);
		if (all_leaf && all_same) {
			bool _val = top_left->val;
			delete top_left;
			delete top_right;
			delete bottom_left;
			delete bottom_right;
			return new Node(_val, true, NULL, NULL, NULL, NULL);
		}
		else return new Node(false, false, top_left, top_right, bottom_left, bottom_right);
	}
public:
	Node* construct(vector<vector<int>>& grid) {
		if (grid.size() == 0) return NULL;
		_grid = grid;
		return dfs(0, 0, grid.size());
	}
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值