剑指Offer-68 树中两个结点的最低公共祖先

题目:

给出一个二叉树,输入两个树节点,求它们的最低公共祖先。
一个树节点的祖先节点包括它本身。
注意:
输入的二叉树不为空;
输入的两个节点一定不为空,且是二叉树中的节点;
在这里插入图片描述

解答:

解法一,使用递归,若两个树节点在根节点的左右子树上,则公共节点为根节点;若两个树节点都在某一子树上,则公共节点在该子树上。这个方法递归都要查询某一子树上是否有节点存在,时间复杂度较高。

# 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 == q or root == p:
            return root
        if not root.left:
            return self.lowestCommonAncestor(root.right, p, q)
        if not root.right:
            return self.lowestCommonAncestor(root.left, p, q)
        pInLeftTree, qInLeftTree = self.isNodeInTree(root.left, p), self.isNodeInTree(root.left, q)
        if pInLeftTree and qInLeftTree:
            return self.lowestCommonAncestor(root.left, p, q)
        if not pInLeftTree and not qInLeftTree:
            return self.lowestCommonAncestor(root.right, p, q)
        return root
        
    def isNodeInTree(self, root, node):
        if root == node:
            return True
        return (root.left and self.isNodeInTree(root.left, node)) or (root.right and self.isNodeInTree(root.right, node))

解法二,先找出从根节点到两个树节点的路径,然后转化为求两个链表的公共节点。

# 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
        """
        pathToP, pathToQ = [], []
        self.iterate(root, p, pathToP)
        self.iterate(root, q, pathToQ)
        diff = len(pathToP) - len(pathToQ)
        if diff < 0:
            startQ = len(pathToQ) -1 + diff
            startP = len(pathToP) - 1
        else:
            startP = len(pathToP) -1 - diff
            startQ = len(pathToQ) - 1
        while(startP >= 0):
            if pathToP[startP] == pathToQ[startQ]:
                return pathToP[startP]
            else:
                startP -= 1
                startQ -= 1
        
    def iterate(self, root, node, path):
        path.append(root)
        if root == node:
            return True
        if root.left:
            if self.iterate(root.left, node, path):
                return True
        if root.right:
            if self.iterate(root.right, node, path):
                return True
        path.pop()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值