【leetcode】236. 二叉树的最近公共祖先
文章目录
- 题目
- 题解
题目
236. 二叉树的最近公共祖先
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
题解
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = Noneclass Solution(object):def lowestCommonAncestor(self, root, p, q):""":type root: TreeNode:type p: TreeNode:type q: TreeNode:rtype: TreeNode"""if root == p or root == q or root is None:return rootleft = self.lowestCommonAncestor(root.left, p , q)right = self.lowestCommonAncestor(root.right, p, q)if left and right:return rootelif left:return leftelse:return right
链接