题目形容

这是 LeetCode 上的 655. 输入二叉树 ,难度为 中等

Tag : 「二叉树」、「递归」

给你一棵二叉树的根节点 root ,请你结构一个下标从 0 开始、大小为 m x n 的字符串矩阵 res ,用以示意树的 格式化布局 。结构此格式化布局矩阵须要遵循以下规定:

  • 树的 高度 为 $height$,矩阵的行数 $m$ 应该等于 $height + 1$。
  • 矩阵的列数 $n$ 应该等于 $2^{height+1 - 1}$ 。
  • 根节点 须要搁置在 顶行 的 正中间 ,对应地位为 $res[0][(n-1)/2]$ 。
  • 对于搁置在矩阵中的每个节点,设对应地位为 $res[r][c]$ ,将其左子节点搁置在 $res[r+1][c-2^{height-r-1}]$ ,右子节点搁置在 $res[r+1][c+2^{height-r-1}]$ 。
  • 持续这一过程,直到树中的所有节点都妥善搁置。
  • 任意空单元格都应该蕴含空字符串 ""

返回结构失去的矩阵 res

示例 1:

输出:root = [1,2]输入:[["","1",""], ["2","",""]]

示例 2:

输出:root = [1,2,3,null,4]输入:[["","","","1","","",""], ["","2","","","","3",""], ["","","4","","","",""]]

提醒:

  • 树中节点数在范畴 $[1, 2^{10}]$ 内
  • $-99 <= Node.val <= 99$
  • 树的深度在范畴 $[1, 10]$ 内

DFS

依据题意,咱们能够先设计 dfs1 递归函数失去树的高度 h,以及与其相干的矩阵行列大小(并初始化矩阵)。

随后依据填充规定,设计 dfs2 递归函数往矩阵进行填充。

Java 代码:

class Solution {    int h, m, n;    List<List<String>> ans;    public List<List<String>> printTree(TreeNode root) {        dfs1(root, 0);        m = h + 1; n = (1 << (h + 1)) - 1;        ans = new ArrayList<>();        for (int i = 0; i < m; i++) {            List<String> cur = new ArrayList<>();            for (int j = 0; j < n; j++) cur.add("");            ans.add(cur);        }        dfs2(root, 0, (n - 1) / 2);        return ans;    }    void dfs1(TreeNode root, int depth) {        if (root == null) return ;        h = Math.max(h, depth);        dfs1(root.left, depth + 1);        dfs1(root.right, depth + 1);    }    void dfs2(TreeNode root, int x, int y) {        if (root == null) return ;        ans.get(x).set(y, String.valueOf(root.val));        dfs2(root.left, x + 1, y - (1 << (h - x - 1)));        dfs2(root.right, x + 1, y + (1 << (h - x - 1)));    }} 

Typescript 代码:

let h: number, m: number, n: number;let ans: string[][];function printTree(root: TreeNode | null): string[][] {    h = 0    dfs1(root, 0)    m = h + 1; n = (1 << (h + 1)) - 1    ans = new Array<Array<string>>()    for (let i = 0; i < m; i++) {        ans[i] = new Array<string>(n).fill("")    }    dfs2(root, 0, (n - 1) / 2)    return ans};function dfs1(root: TreeNode | null, depth: number): void {    if (root == null) return     h = Math.max(h, depth)    dfs1(root.left, depth + 1)    dfs1(root.right, depth + 1)}function dfs2(root: TreeNode | null, x: number, y: number): void {    if (root == null) return     ans[x][y] = root.val + "";    dfs2(root.left, x + 1, y - (1 << (h - x - 1)))    dfs2(root.right, x + 1, y + (1 << (h - x - 1)))}
  • 工夫复杂度:$O(n \times m)$
  • 空间复杂度:$O(n \times m)$

最初

这是咱们「刷穿 LeetCode」系列文章的第 No.655 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,局部是有锁题,咱们将先把所有不带锁的题目刷完。

在这个系列文章外面,除了解说解题思路以外,还会尽可能给出最为简洁的代码。如果波及通解还会相应的代码模板。

为了不便各位同学可能电脑上进行调试和提交代码,我建设了相干的仓库:https://github.com/SharingSou... 。

在仓库地址里,你能够看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其余优选题解。

更多更全更热门的「口试/面试」相干材料可拜访排版精美的 合集新基地

本文由mdnice多平台公布