LeetCode 236. Lowest Common Ancestor of a Binary Tree

题目描述

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

解题思路

求两个节点的最低公共祖先。怎么刻画最低公共祖先呢?给定两个节点 p,q,我们用 Pp 和 Pq 表示从 root 节点到他们的路径,那么这两个路径的最大公共前缀就是从root节点到其最低公共祖先的路径。

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
import copy
class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        self.p = p
        self.q = q
        self.path2p = []
        self.path2q = []
        self.helper(root, [])
        bg = root
        for i in range(min(len(self.path2p), len(self.path2q))):
            if self.path2p[i] == self.path2q[i]:
                if self.path2p[i] == 'l':
                    bg = bg.left
                else:
                    bg = bg.right
            else:
                break
        return bg
    
    
    def helper(self, root, tmp):
        if not root:
            return 
        if root.val == self.q.val:
            self.path2q = copy.deepcopy(tmp)
        if root.val == self.p.val:
            self.path2p = copy.deepcopy(tmp)
        
        tmp.append('l')
        self.helper(root.left, tmp)
        tmp.pop()
        tmp.append('r')
        self.helper(root.right, tmp)
        tmp.pop()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值