problem
solution
option 1
- 先遞迴檢查
p
和q
是否在root
的左子樹 - 如果都在左子樹,則往左子樹搜尋
- 如果都不在,則往右子樹搜尋
- 其餘狀況,則
return root
1 | class Solution { |
option 2 - dfs + postorder traverse
1 | class Solution { |
analysis
- option 1
- time complexity
O(t)
t is the size of the subtree for the first common ancestor on average case,O(n)
on worst case, n is number of nodes in BT - space complexity
O(h)
- time complexity
- option 2
- time complexity
O(n)
n is number of nodes in BT - space complexity
O(h)
h is the height of BT
- time complexity