|
| 1 | +import { createBinaryTree, TreeNode } from "./utilities"; |
| 2 | + |
| 3 | +/** |
| 4 | + * @problem |
| 5 | + * [872. Leaf-Similar Trees](https://leetcode.com/problems/leaf-similar-trees) |
| 6 | + */ |
| 7 | +function leafSimilar(root1: TreeNode, root2: TreeNode): boolean { |
| 8 | + const getLeafs = (root: TreeNode): number[] => { |
| 9 | + if (!root.left && !root.right) { |
| 10 | + return [root.val]; |
| 11 | + } |
| 12 | + const left = root.left ? getLeafs(root.left) : []; |
| 13 | + const right = root.right ? getLeafs(root.right) : []; |
| 14 | + return [...left, ...right]; |
| 15 | + } |
| 16 | + const root1Leafs = getLeafs(root1).join('#'); |
| 17 | + const root2Leafs = getLeafs(root2).join('#'); |
| 18 | + return root1Leafs === root2Leafs; |
| 19 | +}; |
| 20 | + |
| 21 | +export function leafSimilarDBG() { |
| 22 | + const tests = [ |
| 23 | + { |
| 24 | + input: { |
| 25 | + root1: createBinaryTree([3, 5, 1, 6, 2, 9, 8, null, null, 7, 4]), |
| 26 | + root2: createBinaryTree([3, 5, 1, 6, 7, 4, 2, null, null, null, null, null, null, 9, 8]) |
| 27 | + }, |
| 28 | + result: true |
| 29 | + }, |
| 30 | + { |
| 31 | + input: { |
| 32 | + root1: createBinaryTree([1, 2, 3]), |
| 33 | + root2: createBinaryTree([1, 3, 2]) |
| 34 | + }, |
| 35 | + result: false |
| 36 | + }, |
| 37 | + { |
| 38 | + input: { |
| 39 | + root1: createBinaryTree([1]), |
| 40 | + root2: createBinaryTree([1]) |
| 41 | + }, |
| 42 | + result: true |
| 43 | + }, |
| 44 | + ]; |
| 45 | + |
| 46 | + tests.forEach((test, index) => { |
| 47 | + const output = leafSimilar(test.input.root1, test.input.root2); |
| 48 | + const success = output === test.result; |
| 49 | + if (success) { |
| 50 | + console.log(`${index} success`); |
| 51 | + } else { |
| 52 | + console.log(`${index} fail`); |
| 53 | + console.log(`expected ${test.result}`); |
| 54 | + console.log(`got ${output}`); |
| 55 | + } |
| 56 | + }); |
| 57 | +} |
0 commit comments