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);
    }
}
相关推荐
sunny_2 小时前
面试踩大坑!同一段 Node.js 代码,CJS 和 ESM 的执行顺序居然是反的?!99% 的人都答错了
前端·面试·node.js
ayqy贾杰4 小时前
Agent First Engineering
前端·vue.js·面试
Lee川7 小时前
解锁 JavaScript 的灵魂:深入浅出原型与原型链
javascript·面试
swipe8 小时前
从原理到手写:彻底吃透 call / apply / bind 与 arguments 的底层逻辑
前端·javascript·面试
程序员清风9 小时前
小红书二面:Spring Boot的单例模式是如何实现的?
java·后端·面试
belhomme10 小时前
(面试题)Redis实现 IP 维度滑动窗口限流实践
java·面试
Lee川10 小时前
探索JavaScript的秘密令牌:独一无二的`Symbol`数据类型
javascript·面试
AAA梅狸猫10 小时前
消息入队 enqueueMessage
面试
zone773912 小时前
003:RAG 入门-LangChain 读取图片数据
后端·python·面试
zone773912 小时前
002:RAG 入门-LangChain 读取文本
后端·算法·面试