【Leetcode_总结】235. 二叉搜索树的最近公共祖先 - python

Q;

中最近公共祖先的定义为:“对于有根树 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。

链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/

思路:首先二叉搜索树是二叉树的子集,因此这道题完全可以按照 二叉树的最近公共祖先 来做,但是问题就是这样没有用到二叉搜索树的条件,也就是左叶子的值小于根节点,右叶子的值大于根节点,因此这个题两种解决方法

代码:

完全按照二叉树的思想做:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        if(root is None or root==p or root==q):
            return root
        left=self.lowestCommonAncestor(root.left,p,q)
        right=self.lowestCommonAncestor(root.right,p,q)
        if left  and right :
            return root
        if not left :
            return right
        if not right :
            return left
        return None

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        if not root:
            return(root)
        if p.val < root.val and q.val < root.val:
            return(self.lowestCommonAncestor(root.left, p, q))
        if p.val > root.val and q.val > root.val:
            return(self.lowestCommonAncestor(root.right, p, q))  
        return(root)

 

猜你喜欢

转载自blog.csdn.net/maka_uir/article/details/86595687