hello-algo/codes/javascript/modules/PrintUtil.js

87 lines
1.6 KiB
JavaScript
Raw Permalink Normal View History

2022-12-04 23:14:09 +08:00
/**
* File: PrintUtil.js
* Created Time: 2022-12-04
* Author: IsChristina (christinaxia77@foxmail.com)
*/
const { arrToTree } = require('./TreeNode');
/* 打印链表 */
2022-12-04 23:14:09 +08:00
function printLinkedList(head) {
let list = [];
while (head !== null) {
list.push(head.val.toString());
head = head.next;
}
console.log(list.join(' -> '));
2022-12-04 23:14:09 +08:00
}
2023-02-01 03:23:29 +08:00
function Trunk(prev, str) {
this.prev = prev;
this.str = str;
}
2022-12-04 23:14:09 +08:00
/**
* 打印二叉树
2022-12-04 23:14:09 +08:00
* This tree printer is borrowed from TECHIE DELIGHT
* https://www.techiedelight.com/c-program-print-binary-tree/
*/
function printTree(root) {
printTree(root, null, false);
}
/* 打印二叉树 */
2023-11-01 05:14:22 +08:00
function printTree(root, prev, isRight) {
2022-12-04 23:14:09 +08:00
if (root === null) {
return;
}
let prev_str = ' ';
2022-12-04 23:14:09 +08:00
let trunk = new Trunk(prev, prev_str);
printTree(root.right, trunk, true);
if (!prev) {
trunk.str = '———';
2023-11-01 05:14:22 +08:00
} else if (isRight) {
trunk.str = '/———';
prev_str = ' |';
2022-12-04 23:14:09 +08:00
} else {
trunk.str = '\\———';
2022-12-04 23:14:09 +08:00
prev.str = prev_str;
}
showTrunks(trunk);
console.log(' ' + root.val);
2022-12-04 23:14:09 +08:00
if (prev) {
prev.str = prev_str;
}
trunk.str = ' |';
2022-12-04 23:14:09 +08:00
printTree(root.left, trunk, false);
}
function showTrunks(p) {
if (!p) {
return;
}
showTrunks(p.prev);
2022-12-13 21:38:18 +08:00
process.stdout.write(p.str);
2022-12-04 23:14:09 +08:00
}
/* 打印堆 */
function printHeap(arr) {
console.log('堆的数组表示:');
console.log(arr);
console.log('堆的树状表示:');
printTree(arrToTree(arr));
}
2022-12-13 21:38:18 +08:00
module.exports = {
2022-12-04 23:14:09 +08:00
printLinkedList,
printTree,
printHeap,
};