# 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:
return root
if root==q or root==p:
return root
left=self.lowestCommonAncestor(root.left,p,q)
right=self.lowestCommonAncestor(root.right,p,q)
if not left and not right:
return None
if not left:
return right
if not right:
return left
return root
思路:
- 分情况讨论
- 这道题最直观的结果就是,如果两个节点位于root两侧,那么就返回这个根节点
- 然后排除一些情况:1)这个节点为空 2)这个节点就是要找的q或p之一,那么返回这个root(这就是向上传递的情况)
- 然后是处理如何向上传递:
- 再分四个情况:左右都有向上传root,只有一个有传有的那一支,左右都没有传空