|
| 1 | +# 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。 |
| 2 | +# |
| 3 | +# 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大( |
| 4 | +# 一个节点也可以是它自己的祖先)。” |
| 5 | +# |
| 6 | +# 例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4] |
| 7 | +# |
| 8 | +# |
| 9 | +# |
| 10 | +# |
| 11 | +# |
| 12 | +# 示例 1: |
| 13 | +# |
| 14 | +# 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 |
| 15 | +# 输出: 3 |
| 16 | +# 解释: 节点 5 和节点 1 的最近公共祖先是节点 3。 |
| 17 | +# |
| 18 | +# |
| 19 | +# 示例 2: |
| 20 | +# |
| 21 | +# 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 |
| 22 | +# 输出: 5 |
| 23 | +# 解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。 |
| 24 | +# |
| 25 | +# |
| 26 | +# |
| 27 | +# |
| 28 | +# 说明: |
| 29 | +# |
| 30 | +# |
| 31 | +# 所有节点的值都是唯一的。 |
| 32 | +# p、q 为不同节点且均存在于给定的二叉树中。 |
| 33 | +# |
| 34 | +# Related Topics 树 |
| 35 | + |
| 36 | + |
| 37 | +# leetcode submit region begin(Prohibit modification and deletion) |
| 38 | +# Definition for a binary tree node. |
| 39 | +# class TreeNode: |
| 40 | +# def __init__(self, x): |
| 41 | +# self.val = x |
| 42 | +# self.left = None |
| 43 | +# self.right = None |
| 44 | + |
| 45 | +class Solution: |
| 46 | + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': |
| 47 | + if not root or root == p or root == q: return root |
| 48 | + left = self.lowestCommonAncestor(root.left, p, q) |
| 49 | + right = self.lowestCommonAncestor(root.right, p, q) |
| 50 | + if not left: return right |
| 51 | + if not right: return left |
| 52 | + return root |
| 53 | +# leetcode submit region end(Prohibit modification and deletion) |
0 commit comments