剑指offer--面试题50:树中两个结点的最低公共祖先

1. 二叉排序树中求解两个结点的最低公共祖先

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,q的最小公共祖先是r,那么应满足p.val<=r.val and q.val >=r.val,即p,q应在r的两侧
        所以从根节点开始按照某种遍历搜索,检查当前节点是否满足这种关系,如果满足则返回。如果不满足,例如
        p,q都大于r,那么继续搜索r的右子树
        """
        if root:
            if root.val > p.val and root.val > q.val:
                return self.lowestCommonAncestor(root.left, p, q)
            elif root.val < p.val and root.val < q.val:
                return self.lowestCommonAncestor(root.right, p, q)
            else:
                return root
        return None


2.普通二叉树中求解两个结点的最低公共祖先

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
        """
        if root is None or p is None or q is None:
            return None
        path1 = []
        self.getPath(root, p, path1)
        path2 = []
        self.getPath(root, q, path2)
        #if len(path1) == 0 or len(path2) == 0:
        #    return None
        result = None
        for i in range(min(len(path1), len(path2))):
            if path1[i] == path2[i]:
                result = path1[i]
        return result
        
    def getPath(self, root, targetNode, path):
        #当找到targetNode后,targetNode后面的节点就不再append
        if len(path)>0 and path[-1] == targetNode:
            return
        if root:
            path.append(root)
            self.getPath(root.left, targetNode, path)
            self.getPath(root.right, targetNode, path)
            #如果还没有找到targetNode,就pop,不用担心路径上的点会pop掉,因为targetNode加入路径后,他路径上的祖先节点才会执行
            #下面这个if判断(递归栈的顺序)
            if len(path)>0 and path[-1] != targetNode:
                path.pop()#######


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值