UNPKG

avl-promise

Version:

Largely copied from avl (https://www.npmjs.com/package/avl), but with a Promise-based comparator!

63 lines (54 loc) 1.78 kB
/** * Prints tree horizontally * @param {Node} root * @param {Function(node:Node):String} [printNode] * @return {String} */ export function print (root, printNode = (n) => n.key) { var out = []; row(root, '', true, (v) => out.push(v), printNode); return out.join(''); } /** * Prints level of the tree * @param {Node} root * @param {String} prefix * @param {Boolean} isTail * @param {Function(in:string):void} out * @param {Function(node:Node):String} printNode */ function row (root, prefix, isTail, out, printNode) { if (root) { out(`${ prefix }${ isTail ? '└── ' : '├── ' }${ printNode(root) }\n`); const indent = prefix + (isTail ? ' ' : '│ '); if (root.left) row(root.left, indent, false, out, printNode); if (root.right) row(root.right, indent, true, out, printNode); } } /** * Is the tree balanced (none of the subtrees differ in height by more than 1) * @param {Node} root * @return {Boolean} */ export function isBalanced(root) { if (root === null) return true; // If node is empty then return true // Get the height of left and right sub trees var lh = height(root.left); var rh = height(root.right); if (Math.abs(lh - rh) <= 1 && isBalanced(root.left) && isBalanced(root.right)) return true; // If we reach here then tree is not height-balanced return false; } /** * The function Compute the 'height' of a tree. * Height is the number of nodes along the longest path * from the root node down to the farthest leaf node. * * @param {Node} node * @return {Number} */ function height(node) { return node ? (1 + Math.max(height(node.left), height(node.right))) : 0; }