题目描述:给出节点
p
和q
,这两个节点一定在二叉搜索树里面,找出p
和q
的最低公共父节点。
题目链接:Leetcode 235. Lowest Common Ancestor of a Binary Search Tree
这个是二叉搜索树BST 首先想到就是中序遍历,但是中序遍历要记录父节点,上一个父节点以及匹配p
和q
,思绪有点复杂,转而思考其最大的特征,就是左子树节点的值小于根节点、右子树大于根节点(递归)的。
所以如果p
和q
的值都小于根节点,那么就在左子树,都大于根节点就在右边,否则就是在中间(等于的情况也包含)。
所有关于二叉搜索树的题目:
代码如下
class Solution:
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
p_val = p.val
q_val = q.val
n_val = root.val
if p_val < n_val and q_val < n_val:
return self.lowestCommonAncestor(root.left,p,q)
if p_val > n_val and q_val > n_val:
return self.lowestCommonAncestor(root.right,p,q)
return root
迭代的版本
class Solution:
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
s = [root]
p_val = p.val
q_val = q.val
while root:
if root.val < min(p_val,q_val):
root = root.right
elif root.val > max(p_val,q_val):
root = root.left
else:
return root
参考链接
- https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/solution/
- [LeetCode] Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最小共同父节点
- -轻松搞定面试中的二叉树题目
- [LeetCode] Validate Binary Search Tree 验证二叉搜索树
- [LeetCode] Recover Binary Search Tree 复原二叉搜索树
- [LeetCode] Binary Search Tree Iterator 二叉搜索树迭代器
- [LeetCode] Unique Binary Search Trees 独一无二的二叉搜索树
- [LeetCode] Unique Binary Search Trees II 独一无二的二叉搜索树之二
- [LeetCode] Convert Sorted Array to Binary Search Tree 将有序数组转为二叉搜索树](http://www.cnblogs.com/grandyang/p/4295245.html)
- [LeetCode] Convert Sorted List to Binary Search Tree 将有序链表转为二叉搜索树
- [LeetCode] Kth Smallest Element in a BST 二叉搜索树中的第K小的元素
- [LeetCode] Lowest Common Ancestor of a Binary Tree 二叉树的最小共同父节点
- 题目汇总