mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Merge pull request #205 from jojoo15/patch-14
添加 0236. 二叉树的最近公共祖先 python版本
This commit is contained in:
@ -263,8 +263,24 @@ class Solution {
|
||||
```
|
||||
|
||||
Python:
|
||||
|
||||
|
||||
```python
|
||||
# Definition for a binary tree node.
|
||||
# class TreeNode:
|
||||
# def __init__(self, x):
|
||||
# self.val = x
|
||||
# self.left = None
|
||||
# self.right = None
|
||||
//递归
|
||||
class Solution:
|
||||
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
|
||||
if not root or root == p or root == q: return root //找到了节点p或者q,或者遇到空节点
|
||||
left = self.lowestCommonAncestor(root.left,p,q) //左
|
||||
right = self.lowestCommonAncestor(root.right,p,q) //右
|
||||
if left and right: return root //中: left和right不为空,root就是最近公共节点
|
||||
elif left and not right: return left //目标节点是通过left返回的
|
||||
elif not left and right: return right //目标节点是通过right返回的
|
||||
else: return None //没找到
|
||||
```
|
||||
Go:
|
||||
```Go
|
||||
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
|
||||
|
Reference in New Issue
Block a user