归档

427. 建立四叉树

427. 建立四叉树

题目

描述:

给你一个 n * n 矩阵 grid,矩阵由若干 0 和 1 组成。请你用四叉树表示该矩阵 grid。

你需要返回能表示矩阵 grid 的 四叉树 的根结点。

四叉树数据结构中,每个内部节点只有四个子节点。此外,每个节点都有两个属性:

  • val: 储存叶子结点所代表的区域的值。1 对应 True,0 对应 False。注意,当 isLeaf 为 False 时,你可以把 True 或者 False 赋值给节点,两种值都会被判题机制 接受
  • isLeaf: 当这个节点是一个叶子结点时为 True,如果它有 4 个子节点则为 False。
1
2
3
4
5
6
7
8
class Node {
    public boolean val;
    public boolean isLeaf;
    public Node topLeft;
    public Node topRight;
    public Node bottomLeft;
    public Node bottomRight;
}

我们可以按以下步骤为二维区域构建四叉树:

  1. 如果当前网格的值相同(即,全为 0 或者全为 1),将 isLeaf 设为 True,将 val 设为网格相应的值,并将四个子节点都设为 Null 然后停止。
  2. 如果当前网格的值不同,将 isLeaf 设为 False,将 val 设为任意值,然后如下图所示,将当前网格划分为四个子网格。
  3. 使用适当的子网格递归每个子节点。

四叉树划分

示例 1:

示例1图片

  • 输入: grid = [[0,1],[1,0]]
  • 输出: (根据层序遍历的序列化格式) [[0,1],[1,0],[1,1],[1,1],[1,0]]
  • 解释: 在下图四叉树的图示中,0 表示 false,1 表示 True。

示例 2:

示例2图片

  • 输入: grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]
  • 输出: [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
  • 解释:

网格中的所有值都不相同。我们将网格划分为四个子网格。

topLeft,bottomLeft 和 bottomRight 均具有相同的值。

topRight 具有不同的值,因此我们将其再分为 4 个子网格,这样每个子网格都具有相同的值。

解释如下图所示:

解释图片

提示:

  • n == grid.length == grid[i].length
  • n == 2^x 其中 0 <= x <= 6

题解

一个节点代表一个正方形区域

四叉树将矩阵按区域分层表示。如果一个正方形内全部为 0 或全部为 1,用一个叶子节点表示:isLeaf = true,val 记录区域的值。如果区域内同时有两种值,就创建非叶子,将它分成左上、右上、左下、右下四块。

代码的 build(grid, r, c, len) 表示左上角为 (r,c)、边长为 len 的区域,即行区间 [r,r+len)、列区间 [c,c+len)。isUniform 扫描区域,与左上角值比较,遇到不同值立即返回 false。

四个孩子的坐标怎样计算

区域不同值时,令 half = len / 2,四块边长都是 half,左上角分别为:

孩子左上角坐标
topLeft(r,c)
topRight(r,c+half)
bottomLeft(r+half,c)
bottomRight(r+half,c+half)

题目保证矩阵边长为 2 的幂,因此可以不断均分,直到单格。单格必然同值,会生成叶子,不会继续分成零边长区域。

例如 [[0,1],[1,0]] 不是统一区域,根为非叶子,四个孩子依次为值 0、1、1、0 的叶子;若矩阵全为 1,则只生成一个叶子。非叶子的 val 不参与区域值判断,代码固定为 true,含义由四个孩子决定。

复杂度

边长为 n 时,每一层所有区域的扫描总量至多为 $O(n²)$,递归至多 $O(\log n)$ 层,因此时间上界为 $O(n²\log n)$;遇到统一区域或扫描中途发现差异会提前结束,不代表所有输入都花满这一上界。

不计结果树,递归栈深度为 $O(\log n)$,只有常数个局部变量;结果树最坏有 $O(n²)$ 个节点。算法读取原矩阵,不修改格子,也不复制子矩阵。

完整示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

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;
    }
}

public class Main {

    public Node construct(int[][] grid) {
        return build(grid, 0, 0, grid.length);
    }

    private Node build(int[][] grid, int r, int c, int len) {
        if (isUniform(grid, r, c, len)) {
            return new Node(grid[r][c] == 1, true);
        }

        Node node = new Node(true, false);
        int half = len / 2;

        node.topLeft = build(grid, r, c, half);
        node.topRight = build(grid, r, c + half, half);
        node.bottomLeft = build(grid, r + half, c, half);
        node.bottomRight = build(grid, r + half, c + half, half);

        return node;
    }

    private boolean isUniform(int[][] grid, int r, int c, int len) {
        int val = grid[r][c];
        for (int i = r; i < r + len; i++) {
            for (int j = c; j < c + len; j++) {
                if (grid[i][j] != val) {
                    return false;
                }
            }
        }
        return true;
    }

    // 按题面的层序序列化格式输出:每个节点写成 [isLeaf,val],空孩子写 null,去掉末尾的 null
    public static String format(Node root) {
        List<String> res = new ArrayList<>();
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            Node node = queue.poll();
            if (node == null) {
                res.add("null");
                continue;
            }
            res.add("[" + (node.isLeaf ? 1 : 0) + "," + (node.val ? 1 : 0) + "]");
            queue.offer(node.topLeft);
            queue.offer(node.topRight);
            queue.offer(node.bottomLeft);
            queue.offer(node.bottomRight);
        }
        while (!res.isEmpty() && res.get(res.size() - 1).equals("null")) {
            res.remove(res.size() - 1);
        }
        return "[" + String.join(",", res) + "]";
    }

    public static void main(String[] args) {
        Main solution = new Main();

        int[][] grid1 = {
            {0, 1},
            {1, 0}
        };
        System.out.println("示例 1 输入: grid = [[0,1],[1,0]]");
        System.out.println("示例 1 输出: " + format(solution.construct(grid1)));
        System.out.println("-----------------------------");

        int[][] grid2 = {
            {1, 1, 1, 1, 0, 0, 0, 0},
            {1, 1, 1, 1, 0, 0, 0, 0},
            {1, 1, 1, 1, 1, 1, 1, 1},
            {1, 1, 1, 1, 1, 1, 1, 1},
            {1, 1, 1, 1, 0, 0, 0, 0},
            {1, 1, 1, 1, 0, 0, 0, 0},
            {1, 1, 1, 1, 0, 0, 0, 0},
            {1, 1, 1, 1, 0, 0, 0, 0}
        };
        System.out.println("示例 2 输入: 8×8 网格(见题面)");
        System.out.println("示例 2 输出: " + format(solution.construct(grid2)));
    }
}

运行结果(OpenJDK 21.0.12):

1
2
3
4
5
示例 1 输入: grid = [[0,1],[1,0]]
示例 1 输出: [[0,1],[1,0],[1,1],[1,1],[1,0]]
-----------------------------
示例 2 输入: 8×8 网格(见题面)
示例 2 输出: [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
本文由作者按照 CC BY 4.0 进行授权