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);
    }
}
相关推荐
乾坤一气杀25 分钟前
Kotlin 协程原理详解 —— 以 delay 为例
面试
NAGNIP1 小时前
面试官:给我讲一下卷积吧!
算法·面试
NAGNIP1 小时前
一文搞懂卷积神经网络!
算法·面试
ccLianLian2 小时前
leetcode-hot100
算法·leetcode·职场和发展
张元清2 小时前
使用 Hooks 构建无障碍 React 组件
前端·javascript·面试
studyForMokey2 小时前
【Android面试】窗口机制专题
android·面试·职场和发展
萍萍学习3 小时前
蓝桥杯JAVA-4
java·职场和发展·蓝桥杯
XiYang-DING3 小时前
【LeetCode】LCR 019. 验证回文串 II
算法·leetcode·职场和发展
indexsunny3 小时前
互联网大厂Java面试:从Spring Boot到微服务的逐步挑战
java·数据库·spring boot·redis·微服务·面试·电商
郝学胜-神的一滴4 小时前
冷却时间下的任务调度最优解:从原理到实现
数据结构·c++·算法·面试