655.Print Binary Tree 打印二叉樹
阿新 • • 發佈:2017-11-07
rip hidden ret border 微軟 courier into http not
來自為知筆記(Wiz)
Print a binary tree in an m*n 2D string array following these rules:
- The row number
m
should be equal to the height of the given binary tree. - The column number
n
should always be an odd number. - The root node‘s value (in string format) should be put in the exactly middle of the first row it can be put. The column and the row where the root node belongs will separate the rest space into two parts (left-bottom part and right-bottom part
- Each unused space should contain an empty string
""
. - Print the subtrees following the same rules.
Example 1:
Example 2:
Example 3:
Note: The height of binary tree is in the range of [1, 10].
將二叉樹輸出成m * n二維數組
行數m等於二叉樹的高度
列數n總是奇數
根節點位於首行正中間,將其下的空間分成左右兩半。遞歸此過程。
let Tree = require(‘../Helper/Javascript/Tree‘).Tree;
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {string[][]}
*/
var printTree = function (root) {
let rowNum = maxDepth(root);
let colNum = Math.pow(2, rowNum - 1) * 2 - 1;
let res = [];
for (let i = 0; i < rowNum; i++) {
res[i] = [];
for (let j = 0; j < colNum; j++) {
res[i][j] = "";
}
}
setNodeNum(root, res, 0, 0, colNum);
return res;
};
var setNodeNum = function (node, res, depth, left, right) {
if (!node) return;
let mid = Math.floor((left + right) / 2);
res[depth][mid] = String(node.val);
setNodeNum(node.left, res, depth + 1, left, mid);
setNodeNum(node.right, res, depth + 1, mid, right);
}
var maxDepth = function (root) {
if (!root) return 0;
let left = maxDepth(root.left);
let right = maxDepth(root.right);
return Math.max(left, right) + 1;
}
// let root = Tree.CreateTree([1, 2, 5, 3, null, null, null, 4, 5]);
// console.log(printTree(root));
來自為知筆記(Wiz)
655.Print Binary Tree 打印二叉樹