427. Construct Quad Tree

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

对于一个正方形矩阵从(r1,c1)到(r2,c2),midr=(r1 + r2)/2, mirc = (c1 + c2) / 2。

左上矩阵为:(r1 ,c1)->(midr, midc)

左下矩阵为:(midr+1, c1) -> (r2, midc)

右上:(r1, midc + 1)->(midr, c2)

右下:(midr + 1, midc +1)->(r2, c2)

所以递归来做。直到矩阵里面的元素都相同才建立根节点。

/*
// 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:
    Node* construct(vector<vector<int>>& grid) {
        return build(0, 0, grid.size() - 1, grid.size() - 1, grid);
    }
    Node* build(int r1, int c1, int r2, int c2, vector<vector<int>>& grid)
    {
        if(r1 > r2 || c1 > c2) return NULL;
        bool isleaf = true;
        int val = grid[r1][c1];
        for(int i = r1; i <= r2; i++)
            for(int j = c1; j <= c2; j++)
                if(grid[i][j] != val)
                {
                    isleaf = false;
                    break;
                }
        if(isleaf) return new Node(val, true, NULL, NULL, NULL, NULL);
        int midrow = r1 + r2 >> 1;
        int midcol = c1 + c2 >> 1;
        return new Node(false, 0, 
            build(r1, c1, midrow, midcol, grid), // top left
            build(r1, midcol + 1, midrow, c2, grid), // top right
            build(midrow + 1, c1, r2, midcol, grid), // down left
            build(midrow + 1, midcol + 1, r2, c2, grid) // down right
            );
    }
};
发布了44 篇原创文章 · 获赞 0 · 访问量 957

猜你喜欢

转载自blog.csdn.net/weixin_37748689/article/details/102756589