leetcode 236. Lowest Common Ancestor of a Binary Tree(python)

这篇博客介绍了LeetCode第236题——二叉树的最近公共祖先(Lowest Common Ancestor of a Binary Tree)。作者提供了两种解法,包括深度优先搜索(DFS)和广度优先搜索(BFS),并详细解释了每种方法的思路、时间及空间复杂度。此外,还包含了两次刷题时的不同见解和官方解决方案的参考。
摘要由CSDN通过智能技术生成

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).”

Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.
Example 2:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Note:

  • All of the nodes’ values will be unique.
  • p and q are different and both values will exist in the binary tree.

解法1:DFS

利用mid,left,right三个boolean变量代表当前节点为p,q中的一个,或者左子树或右子树中存在p和q中的node
算法流程

  • 从根节点开始遍历整颗树
  • 如果当前节点为p或q中的一个,那么将mid的值设为True然后继续搜索向下搜索当前节点的左子树和右子树
  • left和right的值与mid一样,当recursion到某个level的时候,这个节点的mid值就是上层recursion结果的left和right,所以left和right即为recurse_tree的返回值
  • 若mid,left,right这三个值的和大于等于2,证明当前节点即为我们要寻找的答案
class Solution(object):
    def __init__(self):
        self.ans = None
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        def recurse_tree(current_node):
            if not current_node:
                return False
            
            left = recurse_tree(current_node.left)
            right = recurse_tree(current_node.right)
            
            mid = (current_node==p or current_node==q)
            if mid+left+right >= 2:
                self.ans = current_node
                
            return mid or left or right

时间复杂度:O(N), N为节点的个数,因为最差的情况我们可能需要访问整颗树的所有节点
空间复杂度:O(N), N同样为节点的个数,因为这棵树的最大深度可以是N

二刷DFS1

二刷的时候看到一种非常intuitive但是比较慢的解法

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值