Leetcode腾讯精选_编号:235 --python
2019-03-01 23:16
363 查看
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]
示例 1:
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
输出: 6
解释: 节点 2 和节点 8 的最近公共祖先是 6。
示例 2:
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
输出: 2
解释: 节点 2 和节点 4 的最近公共祖先是 2, 因为根据定义最近公共祖先节点可以为节点本身。
说明:
所有节点的值都是唯一的。
p、q 为不同节点且均存在于给定的二叉搜索树中。
看了别人的。。。。
# 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, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ if not root : return root if root == p or root == q: return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) if left is not None and right is not None: return root if left is None: return right return left
相关文章推荐
- Leetcode腾讯精选_编号:344 --python
- Leetcode腾讯精选_编号:557 --python
- Leetcode腾讯精选_编号:236 --python
- Leetcode腾讯精选_编号:237 --python
- Leetcode腾讯精选_编号:292 --python
- leetcode235题 题解 翻译 C语言版 Python版
- leetcode-python 第八周
- LeetCode 623 在二叉树中增加一行 Python
- 47. Permutation II Leetcode Python
- 55. Jump Game Leetcode Python
- leetcode String to Integer (atoi) python
- [python]Leetcode2-Add Two Numbers
- [leetcode]Intersection of Two Linked Lists —— 熟悉python
- LeetCode 169. Majority Element(Python)
- [Leetcode,python] Hamming Distance 汉明距离
- python3 bs4 requests 腾讯新闻 标题 链接获取 小试牛刀
- 【LeetCode】Python实现-219. 存在重复元素 II
- Leetcode 451 python 解题报告
- [LeetCode] 021. Merge Two Sorted Lists (Easy) (C++/Python)
- [Leetcode] 15.3Sum @python