|
| 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 | +// Approach 3: |
| 13 | +// Time Complexity: O(n) |
| 14 | +// Space Complexity: O(n), due to the recursion stack |
| 15 | + |
| 16 | +function maxDepth(root: TreeNode | null): number { |
| 17 | + if (!root) return 0; |
| 18 | + |
| 19 | + return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); |
| 20 | +} |
| 21 | + |
| 22 | +// Approach 2: |
| 23 | +// Time Complexity: O(n) |
| 24 | +// Space Complexity: O(n) |
| 25 | + |
| 26 | +// function maxDepth(root: TreeNode | null): number { |
| 27 | +// if (!root) return 0; |
| 28 | + |
| 29 | +// let maxDepth = 0; |
| 30 | +// let stack: Array<[TreeNode, number]> = [[root, 1]]; |
| 31 | + |
| 32 | +// while (stack.length > 0) { |
| 33 | +// const item = stack.pop(); |
| 34 | + |
| 35 | +// if (!item) continue; |
| 36 | + |
| 37 | +// const [node, depth] = item; |
| 38 | + |
| 39 | +// maxDepth = Math.max(maxDepth, depth); |
| 40 | + |
| 41 | +// if (node.left) { |
| 42 | +// stack.push([node.left, depth + 1]); |
| 43 | +// } |
| 44 | + |
| 45 | +// if (node.right) { |
| 46 | +// stack.push([node.right, depth + 1]); |
| 47 | +// } |
| 48 | +// } |
| 49 | + |
| 50 | +// return maxDepth; |
| 51 | +// } |
| 52 | + |
| 53 | + |
| 54 | +// Approach 1 |
| 55 | +// Time Compleixty:O(n) |
| 56 | +// Space Complexity:O(n), due to the recursion stack |
| 57 | + |
| 58 | +// function maxDepth(root: TreeNode | null): number { |
| 59 | +// let maxCnt = 0; |
| 60 | + |
| 61 | +// const dfs = (node: TreeNode | null, cnt: number) => { |
| 62 | +// if (!node) { |
| 63 | +// maxCnt = Math.max(maxCnt, cnt); |
| 64 | +// return; |
| 65 | +// } |
| 66 | + |
| 67 | +// dfs(node.left, cnt + 1); |
| 68 | +// dfs(node.right, cnt + 1); |
| 69 | +// }; |
| 70 | + |
| 71 | +// dfs(root, 0); |
| 72 | + |
| 73 | +// return maxCnt; |
| 74 | +// } |
| 75 | + |
0 commit comments