day82(2.10)——leetcode面试经典150

427. 建立四叉树

427. 建立四叉树

这个题目把我吓到了哈哈哈 如此之多

题目:

题解:

java 复制代码
/*
// Definition for a QuadTree node.
class Node {
    public boolean val;
    public boolean isLeaf;
    public Node topLeft;
    public Node topRight;
    public Node bottomLeft;
    public Node bottomRight;

    
    public Node() {
        this.val = false;
        this.isLeaf = false;
        this.topLeft = null;
        this.topRight = null;
        this.bottomLeft = null;
        this.bottomRight = null;
    }
    
    public Node(boolean val, boolean isLeaf) {
        this.val = val;
        this.isLeaf = isLeaf;
        this.topLeft = null;
        this.topRight = null;
        this.bottomLeft = null;
        this.bottomRight = null;
    }
    
    public Node(boolean val, boolean isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bottomRight) {
        this.val = val;
        this.isLeaf = isLeaf;
        this.topLeft = topLeft;
        this.topRight = topRight;
        this.bottomLeft = bottomLeft;
        this.bottomRight = bottomRight;
    }
}
*/

class Solution {
    public Node construct(int[][] grid) {
        int n = grid.length;
        return build(grid, 0, n-1, 0, n-1);
    }

    Node build(int[][] grid, int l1, int r1, int l2, int r2) {
        int flag = 0;
        int d = grid[l1][l2];
        for(int i=l1;i<=r1;i++) {
            for(int j=l2;j<=r2;j++) {
                if(grid[i][j]!=d) {
                    flag=1;
                    break;
                }
            }
            if(flag==1) {
                break;
            }
        }

        //如果该区域都相等,直接返回Node
        if(flag==0) {
            return new Node(d == 1, true);
        }

        int mid1 = (l1+r1)/2;
        int mid2 = (l2+r2)/2;

        Node tL = build(grid, l1, mid1, l2, mid2);
        Node tR = build(grid, l1, mid1, mid2+1, r2);
        Node bL = build(grid, mid1+1, r1, l2, mid2);
        Node bR = build(grid, mid1+1, r1, mid2+1, r2);
       
        return new Node(false, false, tL, tR, bL, bR);
    }
}
相关推荐
李日灐31 分钟前
【优选算法5】位运算经典算法面试题
后端·算法·面试·位运算
ayqy贾杰1 小时前
过去三年我做对了一件事
前端·面试·ai编程
Raink老师2 小时前
用100道题拿下你的算法面试(链表篇-5):删除链表的倒数第 N 个节点
算法·链表·面试
qq_296553272 小时前
[特殊字符] 数组中的递增三元组:O(n) 时间高效查找,面试必考!
数据结构·算法·面试·职场和发展·组合模式·柔性数组
逻辑驱动的ken2 小时前
Java高频面试考点场景题26
java·开发语言·面试·职场和发展·求职招聘
星辰_mya2 小时前
领域驱动设计(DDD)“老中医”治理订单
java·后端·面试·架构
张元清2 小时前
React 浏览器标签页 UX:用标题、Favicon 和通知把用户拉回来
前端·javascript·面试
Lkstar2 小时前
读完红宝书和YDKJS,我终于搞懂了原型链、闭包和this
javascript·面试
alphaTao2 小时前
LeetCode 每日一题 2026/5/4-2026/5/10
算法·leetcode·职场和发展
Cosolar2 小时前
大模型量化技术全景深度解析:从FP16到INT4的完整演进与实战落地
人工智能·面试·架构