[LeetCode] 236. Lowest Common Ancestor of a Binary Tree @ python

一.题目:
求二叉树中两个节点的最近公共祖先.
二.解题思路:
首先,很通俗的解法就是找到两个节点的路径,然后对两条路径进行判断,分叉口的上一个节点就是这两个节点的最近公共祖先.
代码如下:

# 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
        """
        #常规解法
        p_result = []
        q_result = []
       	def getPath1(root,node,path,result):
            if root == None:
                return False
            path.append(root)
            if root == node:
                result.append(path[:])
            if root.left:
                getPath1(root.left,node,path,result)
            if root.right:
                getPath1(root.right,node,path,result)
            path.pop()
            
        def getLastCommonNode(path1,path2):
            pLast=None
            i=0
            while i<min(len(path1),len(path2)):
                if path1[i]==path2[i]:
                    pLast=path1[i]
                    i+=1
                else:
                    break
            return pLast
        if not root or not p or not q:
            return None
        getPath1(root,p,[],p_result)
        getPath1(root,q,[],q_result)
        p_result = p_result[0]
        q_result = q_result[0]
        return getLastCommonNode(p_result,q_result)

此外还有一种递归方法,想不到啊=-=
直接贴代码

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
        if root in (p,q):
            return root
        left = self.lowestCommonAncestor(root.left,p,q)
        right = self.lowestCommonAncestor(root.right,p,q)
        return root if left and right else left or right
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值