|
| 1 | + |
| 2 | +class TreeNode { |
| 3 | + constructor(value) { |
| 4 | + this.val = value; |
| 5 | + this.parent = this.left = this.right = null; |
| 6 | + } |
| 7 | +} |
| 8 | + |
| 9 | +export class Tree { |
| 10 | + constructor() { |
| 11 | + this.root = null; |
| 12 | + } |
| 13 | + |
| 14 | + add(value) { |
| 15 | + let node = new TreeNode(value); |
| 16 | + if (!this.root) { |
| 17 | + this.root = node; |
| 18 | + } |
| 19 | + else { |
| 20 | + let n = this.root, |
| 21 | + branch; |
| 22 | + while (n) { |
| 23 | + branch = value < n.val ? 'left' : 'right'; |
| 24 | + if (!n[branch]) { |
| 25 | + break; |
| 26 | + } |
| 27 | + n = n[branch]; |
| 28 | + } |
| 29 | + node.parent = n; |
| 30 | + n[branch] = node; |
| 31 | + } |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +class LinkedListNode { |
| 36 | + constructor(value, next) { |
| 37 | + this.val = value; |
| 38 | + this.next = next || null; |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +export class LinkedList { |
| 43 | + constructor() { |
| 44 | + this.head = this.tail = null; |
| 45 | + } |
| 46 | + |
| 47 | + prepend(value) { |
| 48 | + if (!this.head) { |
| 49 | + this.head = this.tail = new LinkedListNode(value); |
| 50 | + } |
| 51 | + else { |
| 52 | + this.head = new LinkedListNode(value, this.head); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + append(value) { |
| 57 | + if (!this.head) { |
| 58 | + this.head = this.tail = new LinkedListNode(value); |
| 59 | + } |
| 60 | + else { |
| 61 | + this.tail = this.tail.next = new LinkedListNode(value); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + toArray() { |
| 66 | + let arr = [], |
| 67 | + node = this.head; |
| 68 | + while (node) { |
| 69 | + arr.push(node.val); |
| 70 | + node = node.next; |
| 71 | + } |
| 72 | + return arr; |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +function findDepth(cache, node, depth) { |
| 77 | + if (!node) { |
| 78 | + if (depth < cache.min) { |
| 79 | + cache.min = depth; |
| 80 | + } |
| 81 | + if (depth > cache.max) { |
| 82 | + cache.max = depth; |
| 83 | + } |
| 84 | + } else { |
| 85 | + findDepth(cache, node.left, depth + 1); |
| 86 | + findDepth(cache, node.right, depth + 1); |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +export function isBalanced(tree) { |
| 91 | + if (!tree || !tree.root) { |
| 92 | + return true; |
| 93 | + } |
| 94 | + |
| 95 | + let node = tree.root, |
| 96 | + cache = { |
| 97 | + min: Number.MAX_SAFE_INTEGER, |
| 98 | + max: Number.MIN_SAFE_INTEGER |
| 99 | + }; |
| 100 | + |
| 101 | + findDepth(cache, node, 0); |
| 102 | + return cache.max - cache.min <= 1; |
| 103 | +} |
0 commit comments