|
| 1 | +# 0236. Lowest Common Ancestor of a Binary Tree |
| 2 | + |
| 3 | +Difficulty: medium |
| 4 | +Link: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ |
| 5 | +highlight: 紀錄是否在該個子樹內 |
| 6 | +Topics: DFS-BFS |
| 7 | + |
| 8 | +# Clarification |
| 9 | + |
| 10 | +1. Check the inputs and outputs |
| 11 | + |
| 12 | +# Solution |
| 13 | + |
| 14 | +### Thought Process |
| 15 | + |
| 16 | +- Recursive [[ref-leetcode-solution]](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/solution/) |
| 17 | + - 條件 |
| 18 | + - current == null: return False |
| 19 | + - else return mid or left or right |
| 20 | + - mid = current == q or q |
| 21 | + - left = dfs(root.left) |
| 22 | + - right = dfs(root.right) |
| 23 | + - 若 mid , left, right 有兩個 == True |
| 24 | + - ⇒ 這個node 就是 LCA |
| 25 | + |
| 26 | +  |
| 27 | + |
| 28 | +  |
| 29 | + |
| 30 | +  |
| 31 | + |
| 32 | +  |
| 33 | + |
| 34 | +  |
| 35 | + |
| 36 | +  |
| 37 | + |
| 38 | +  |
| 39 | + |
| 40 | +  |
| 41 | + |
| 42 | +  |
| 43 | + |
| 44 | +- Implement |
| 45 | + |
| 46 | + ```python |
| 47 | + # Definition for a binary tree node. |
| 48 | + # class TreeNode: |
| 49 | + # def __init__(self, x): |
| 50 | + # self.val = x |
| 51 | + # self.left = None |
| 52 | + # self.right = None |
| 53 | + |
| 54 | + class Solution: |
| 55 | + def __init__(self): |
| 56 | + self.ans = None |
| 57 | + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': |
| 58 | + |
| 59 | + def dfs(current): |
| 60 | + |
| 61 | + if not current: |
| 62 | + return False |
| 63 | + |
| 64 | + left = dfs(current.left) |
| 65 | + right = dfs(current.right) |
| 66 | + mid = False |
| 67 | + |
| 68 | + if current == p or current == q: |
| 69 | + mid = True |
| 70 | + |
| 71 | + if mid + left + right >= 2: |
| 72 | + self.ans = current |
| 73 | + |
| 74 | + return mid or left or right |
| 75 | + |
| 76 | + dfs(root) |
| 77 | + return self.ans |
| 78 | + ``` |
| 79 | + |
| 80 | + |
| 81 | +### Complexity |
| 82 | + |
| 83 | +- Time complexity: O(N) |
| 84 | + - N: number of nodes in binary tree |
| 85 | + - search all nodes |
| 86 | +- Space complexity: O(N) |
| 87 | + - recursion stack |
| 88 | + - skewed binary tree |
0 commit comments