力扣每日一题0822-655. 输出二叉树

100 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第22天,点击查看活动详情

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

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

返回构造得到的矩阵 **res

示例 1:

print1-tree.jpg

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

示例 2:

print2-tree.jpg

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

深度优先搜索

我们可以通过深度优先搜索来解决此题。首先通过深度优先搜索来得到二叉树的高度 height\textit{height}(注意高度从 0 开始),然后创建一个行数为 m=height+1m = \textit{height} + 1,列数为 n=2height+11n = 2^{\textit{height} + 1} - 1 的答案数组 res\textit{res} 放置节点的值(字符串形式)。根节点的值应当放在当前空间的第一行正中间。根节点所在的行与列会将剩余空间划分为两部分(左下部分和右下部分),然后递归地将左子树输出在左下部分空间,右子树输出在右下部分空间即可。

var printTree = function(root) {
    const calDepth = (root) => {
        let h = 0;
        if (root.left) {
            h = Math.max(h, calDepth(root.left) + 1);
        }
        if (root.right) {
            h = Math.max(h, calDepth(root.right) + 1);
        }
        return h;
    }

    const dfs = (res, root, r, c, height) => {
        res[r][c] = root.val.toString();
        if (root.left) {
            dfs(res, root.left, r + 1, c - (1 << (height - r - 1)), height);
        }
        if (root.right) {
            dfs(res, root.right, r + 1, c + (1 << (height - r - 1)), height);
        }
    }

    const height = calDepth(root);
    const m = height + 1;
    const n = (1 << (height + 1)) - 1;
    const res = new Array(m).fill(0).map(() => new Array(n).fill(''));
    dfs(res, root, 0, Math.floor((n - 1) / 2), height);
    return res;
};