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);
    }
}
相关推荐
.道阻且长.7 小时前
2.LeetCode算法习题讲解--双指针--复写零
算法·leetcode·职场和发展
kyriewen10 小时前
面试官问"这段逻辑为什么这样写"——我才发现,这半年我写的代码,我自己都解释不了
前端·javascript·面试
大龄秃头程序员12 小时前
深入梳理 UIView touch 事件全链路原理与实战
面试
众人皆醒我独醉13 小时前
Token:AI 世界的基本粒子——不是"字",是统计上最优的"字符组合"
后端·面试·llm
古法安卓13 小时前
Android-DeviceStorageMonitorService 流程分析
java·面试·android studio
预知同行14 小时前
从 MCP 到 CLI:AI Agent 工具链的架构演进与实战抉择
前端·面试
黄敬峰14 小时前
从零搞懂React受控与非受控组件——一个Demo串起表单处理全流程
面试
一只齐刘海的猫14 小时前
【Leetcode】乘积最大子数组
算法·leetcode·职场和发展
GitLqr18 小时前
玩转 Dart typedef:不仅是函数别名那么简单
flutter·面试·dart
向阳而生自媒体18 小时前
2026年MBA面试自我介绍怎么说?3分钟/5分钟版本怎么准备?
面试·职场和发展