|
| 1 | +class TreeNode: |
| 2 | + def __init__(self, val=0, left=None, right=None): |
| 3 | + self.val = val |
| 4 | + self.left = left |
| 5 | + self.right = right |
| 6 | + |
| 7 | +""" |
| 8 | + 1. Problem Summary / Clarifications / TDD: |
| 9 | + Case 1: Return 2 |
| 10 | + 1 |
| 11 | + / \ |
| 12 | + 2 3 |
| 13 | + / \ \ |
| 14 | + 4 5 6 |
| 15 | + / \ \ |
| 16 | + 7 8 9 |
| 17 | +
|
| 18 | + Case 2: Return 10 |
| 19 | + 1 |
| 20 | + / \ |
| 21 | + 2 3 |
| 22 | + / \ \ |
| 23 | + 4 5 6 |
| 24 | + / \ \ |
| 25 | + 7 8 9 |
| 26 | + / |
| 27 | + 10 |
| 28 | +
|
| 29 | + 2. Inuition |
| 30 | + - DFS traversal: for each branch, return its height and its subtree with all deepest nodes |
| 31 | + - If left height == right hight, return root |
| 32 | + - If left height > right height, return left substree |
| 33 | + - If left height < right height, return right substree |
| 34 | + |
| 35 | + 3. Implementation: |
| 36 | + 4. Tests: |
| 37 | + - All cases above |
| 38 | + - Edge cases: empty tree, a tree with one node |
| 39 | + - Special cases: Tree as a linked list, balanced tree |
| 40 | + 1 1 |
| 41 | + \ / |
| 42 | + 2 2 |
| 43 | + \ / |
| 44 | + 3 3 |
| 45 | +
|
| 46 | + 4. Complexity Analysis: |
| 47 | + Time Complexity: O(N): we need to visit all nodes |
| 48 | + Space Complexity: |
| 49 | + - Worst case: O(N): when the tree looks like a linked-list. |
| 50 | + - Best case: O(height): when the tree is balanced. |
| 51 | +
|
| 52 | +""" |
| 53 | + |
| 54 | +class SolutionDFS: |
| 55 | + |
| 56 | + def subtree_with_all_deepest(self, root: TreeNode) -> TreeNode: |
| 57 | + |
| 58 | + return self.dfs(root)[1] |
| 59 | + |
| 60 | + def dfs(self, root: TreeNode) -> (int, TreeNode): |
| 61 | + if root is None: |
| 62 | + return 0, None |
| 63 | + |
| 64 | + l_height, l_subtree = self.dfs(root.left) |
| 65 | + r_height, r_subtree = self.dfs(root.right) |
| 66 | + |
| 67 | + return max(l_height, r_height) + 1, l_subtree if l_height > r_height else r_subtree if l_height < r_height else root |
0 commit comments