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)](