数据结构与算法之LeetCode-655. 输出二叉树 - 力扣(LeetCode)

655. 输出二叉树 - 力扣(LeetCode)

  • 先构建高度 height
  • 在构建层数,根据高度和层数得到数的位置
DFS
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {string[][]}
 */
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;
};

执行结果:通过

执行用时:64 ms, 在所有 JavaScript 提交中击败了34.38%的用户

内存消耗:41.4 MB, 在所有 JavaScript 提交中击败了87.50%的用户

通过测试用例:73 / 73

BFS
var printTree = function(root) {
    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(''));
    const queue = [];
    queue.push([root, 0, Math.floor((n - 1) / 2)]);
    while (queue.length > 0) {
        const t = queue.shift();
        const node = t[0];
        let r = t[1], c = t[2];
        res[r][c] = node.val.toString();
        if (node.left) {
            queue.push([node.left, r + 1, c - (1 << (height - r - 1))]);
        }
        if (node.right) {
            queue.push([node.right, r + 1, c + (1 << (height - r - 1))]);
        }
    }
    return res;
};

const CalDepth = (root) => {
    let res = -1;
    const queue = [root];
    while (queue.length > 0) {
        let len = queue.length;
        res++;
        while (len > 0) {
            len--;
            const t = queue.shift();
            if (t.left) {
                queue.push(t.left);
            }
            if (t.right) {
                queue.push(t.right);
            }
        }
    }
    return res;
}
参考链接

655. 输出二叉树 - 力扣(LeetCode)

输出二叉树 - 输出二叉树 - 力扣(LeetCode)

[[Python/Java/TypeScript/Go] DFS - 输出二叉树 - 力扣(LeetCode)](

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值