zoukankan      html  css  js  c++  java
  • leetcode 235 二叉搜索树最近公共祖先

    leetcode 235 二叉搜索树最近公共祖先

    题目描述:

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

    解法一:自己的写法,贼傻

    # 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
            """
            def findPath(root,num,tmp,path):
                if not root:
                    return
                if root.val == num.val:
                    path.append(tmp + [root])
                    return
                findPath(root.left,num,tmp+[root],path)
                findPath(root.right,num,tmp+[root],path)
            minn = min(p.val, q.val)
            maxn = max(p.val, q.val)
            p_path = []
            q_path = []
            findPath(root,p,[],p_path)
            findPath(root,q,[],q_path)
            p_path = p_path[0]#[::-1]
            q_path = q_path[0]#[::-1]
            lenm = min(len(p_path),len(q_path))
            for i in range(0,lenm):
                if p_path[i].val == q_path[i].val:
                    res = p_path[i]
            return res
    

    网上的写法

    # 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':
            min_ = min(p.val,q.val)
            max_ = max(p.val,q.val)
            if not root:
                return 
            if min_ <= root.val <= max_:
                return root
            else:
                l = self.lowestCommonAncestor(root.left, p, q)
                r = self.lowestCommonAncestor(root.right, p, q)
                if l:
                    return l
                if r:
                    return r
    
  • 相关阅读:
    Vue2 组件注册
    Vue2 CSS 过渡
    Vue2 过滤器
    Vue2 路由
    网页一次滚动一屏幕效果
    JavaScript作用域-声明提升(个人总结)
    JS函数作用域提升
    如何以计算机的方式去思考
    常用Git命令总结
    关于RBAC(Role-Base Access Control)的理解(转)
  • 原文地址:https://www.cnblogs.com/curtisxiao/p/11247858.html
Copyright © 2011-2022 走看看