Day5 二叉搜索树最近的公共祖先【树】

题目:
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。

思路:
二叉搜索树:空树或者 左子树都比根小且右子树都比根大的二叉树
利用二叉搜索树的特性

代码:

# 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 None
        elif root.val>p.val and root.val>q.val:#pq都在左子树
            return self.lowestCommonAncestor(root.left,p,q)
        elif root.val<p.val and root.val<q.val:#pq都在右子树
            return self.lowestCommonAncestor(root.right,p,q)
        else:
            return root

猜你喜欢

转载自blog.csdn.net/weixin_47128888/article/details/112645177