首页 > 其他 > 详细

[树] leetcode 427 Construct Quad Tree

时间:2019-08-03 19:46:39      阅读:75      评论:0      收藏:0      [点我收藏+]

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!