【LeetCode 简单题】64-二叉搜索树的最近公共祖先

声明:

今天是第64道题。给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。以下所有代码经过楼主验证都能在LeetCode上执行成功,代码也是借鉴别人的,在文末会附上参考的博客链接,如果侵犯了博主的相关权益,请联系我删除

(手动比心ღ( ´・ᴗ・` ))

正文

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

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

例如,给定如下二叉搜索树:  root = [6,2,8,0,4,7,9,null,null,3,5]

        _______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0      _4       7       9
         /  \
         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 为不同节点且均存在于给定的二叉搜索树中。

解法1。审题得知这是1棵二叉搜索树,意味着比当前节点大的元素在右边,小的在左边所以给定p、q,只需遍历左右子树找到介于这两者之间(闭区间)的元素即可,代码如下。

执行用时: 112 ms, 在Lowest Common Ancestor of a Binary Search Tree的Python提交中击败了29.72% 的用户

# 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 None
        min_ele = min(p,q)
        max_ele = max(p,q)

        if root.val >= min_ele and root.val <= max_ele:
            return root
        else:
            l = self.lowestCommonAncestor(root.left,p,q)
            r = slef.lowestCommonAncestor(root.right,p,q)
            
            if l:
                return l
            if r:
                return r
        

解法2。分别用给定的p、q这2个值逐一遍历比较二叉树的节点元素直到索引到自身,顺便用容器stack存放比较过的元素值(包括自身),遍历stack,如果遇到不相等的元素(就是p、q)就返回上一个节点(就是父节点),遍历完了就返回stack最后一个元素,代码如下。

执行用时: 96 ms, 在Lowest Common Ancestor of a Binary Search Tree的Python提交中击败了61.29% 的用户

# 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 None
        s_p = []
        s_q = []
        self.search(root,p,s_p)
        self.search(root,q,s_q)
        
        n = min(len(s_p),len(s_q))
        for i in range(n):
            if s_p[i] != s_q[i]
                return s_q[i-1]
        return s_q[n-1]


    def search(self,root,x,stack):
        stack.append(root)
        if root.val < x.val:
            self.search(root.right, x, stack)
        elif root.val > x.val:
            self.search(root.left, x, stack)
        else:
            return

结尾

解法1:https://blog.csdn.net/qq_34364995/article/details/80657907

解法2:LeetCode

猜你喜欢

转载自blog.csdn.net/weixin_41011942/article/details/83614683
今日推荐