Skip to content

Commit 32fcc12

Browse files
committed
problem: 0236 LCA of a binary tree
1 parent f96ac86 commit 32fcc12

File tree

10 files changed

+88
-0
lines changed

10 files changed

+88
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
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+
![Untitled](./Untitled.png)
27+
28+
![Untitled](./Untitled%201.png)
29+
30+
![Untitled](./Untitled%202.png)
31+
32+
![Untitled](./Untitled%203.png)
33+
34+
![Untitled](./Untitled%204.png)
35+
36+
![Untitled](./Untitled%205.png)
37+
38+
![Untitled](./Untitled%206.png)
39+
40+
![Untitled](./Untitled%207.png)
41+
42+
![Untitled](./Untitled%208.png)
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
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading

0 commit comments

Comments
 (0)