|
| 1 | +class TreeNode { |
| 2 | + val: number; |
| 3 | + left: TreeNode | null; |
| 4 | + right: TreeNode | null; |
| 5 | + constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { |
| 6 | + this.val = val === undefined ? 0 : val; |
| 7 | + this.left = left === undefined ? null : left; |
| 8 | + this.right = right === undefined ? null : right; |
| 9 | + } |
| 10 | +} |
| 11 | + |
| 12 | +function maxDepthBFS(root: TreeNode | null): number { |
| 13 | + if (root === null) { |
| 14 | + return 0; |
| 15 | + } |
| 16 | + |
| 17 | + const queue = [root]; |
| 18 | + let depth = 0; |
| 19 | + |
| 20 | + while (queue.length !== 0) { |
| 21 | + const size = queue.length; |
| 22 | + |
| 23 | + for (let i = 0; i < size; i++) { |
| 24 | + const node = queue.shift(); |
| 25 | + |
| 26 | + if (node.left) { |
| 27 | + queue.push(node.left); |
| 28 | + } |
| 29 | + if (node.right) { |
| 30 | + queue.push(node.right); |
| 31 | + } |
| 32 | + } |
| 33 | + depth += 1; |
| 34 | + } |
| 35 | + |
| 36 | + return depth; |
| 37 | +} |
| 38 | + |
| 39 | +function maxDepthDSF(root: TreeNode | null): number { |
| 40 | + if (root === null) { |
| 41 | + return 0; |
| 42 | + } |
| 43 | + |
| 44 | + const stack = [{ node: root, depth: 1 }]; |
| 45 | + let maxDepth = 0; |
| 46 | + |
| 47 | + while (stack.length !== 0) { |
| 48 | + const { node, depth } = stack.pop(); |
| 49 | + |
| 50 | + maxDepth = Math.max(maxDepth, depth); |
| 51 | + |
| 52 | + if (node.right) { |
| 53 | + stack.push({ node: node.right, depth: depth + 1 }); |
| 54 | + } |
| 55 | + |
| 56 | + if (node.left) { |
| 57 | + stack.push({ node: node.left, depth: depth + 1 }); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + return maxDepth; |
| 62 | +} |
| 63 | + |
| 64 | +function maxDepthRecursion(root: TreeNode | null): number { |
| 65 | + if (root === null) { |
| 66 | + return 0; |
| 67 | + } |
| 68 | + |
| 69 | + return ( |
| 70 | + 1 + Math.max(maxDepthRecursion(root.left), maxDepthRecursion(root.right)) |
| 71 | + ); |
| 72 | +} |
| 73 | + |
| 74 | +const tree = new TreeNode( |
| 75 | + 3, |
| 76 | + new TreeNode(9), |
| 77 | + new TreeNode(20, new TreeNode(15), new TreeNode(7)) |
| 78 | +); |
| 79 | + |
| 80 | +console.log(maxDepthBFS(tree)); |
| 81 | +console.log(maxDepthDSF(tree)); |
| 82 | +console.log(maxDepthRecursion(tree)); |
0 commit comments