"""
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).”
Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]
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.
"""
"""
本题两种解法。第一种非递归的方法
用queue来存储结点遍历
用dict{root, parent[root]}来存储每个结点的父亲结点
然后用一个set存储p的所有父辈结点
再遍历q的每个父亲结点查找是否再set中
如果找到即为p,q结点的最近公共祖先
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None class Solution1:
def lowestCommonAncestor(self, root, p, q):
queue = [root] #用来层次遍历
parent = {root: None} #用dict存储父亲结点
while queue:
node = queue.pop()
if node.left:
parent[node.left] = node #存父亲结点
queue.append(node.left) #入队
if node.right:
parent[node.right] = node
queue.append(node.right)
res = set() #set集合是一个无序不重复元素的序列
while p: #res=() 这是把res定义为tuple,tuple是只能查看的list
res.add(p) #将p的所有父辈结点放入set里
p = parent[p]
while q not in res: #q向上找到相同的父亲结点
q = parent[q]
return q """
第二种是递归写法:没有理解
传送门:https://blog.csdn.net/qq_17550379/article/details/95903394
树型问题首先考虑递归,对于每个树中的p和q只会有一下几种情况
1. p在左子树中,q在右子树中
2. q在左子树中,p在右子树中
3. p和q都在左子树中
4. p和q都在右子树中
对于第一种和第二种情况很简单,p和q的最近公共祖先就是root。
对于第三种情况我们只需递归向左子树找,第四种情况我们只需递归向右子树找。接着思考边界情况。
当p==root or q==root的时候,我们返回root即可(因为要找最近公共祖先,继续遍历的话,就不可能是其祖先了)。
那么这里就有一个迷惑人的地方了,请认真思考第一种和第二种情况下,左右子树的递归返回结果是什么?就是p和q。
""" class Solution2:
def lowestCommonAncestor(self, root, p, q):
if not root or root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
return left if left else right

leetcode236 Lowest Common Ancestor of a Binary Tree的更多相关文章

  1. leetcode 235. Lowest Common Ancestor of a Binary Search Tree 236. Lowest Common Ancestor of a Binary Tree

    https://www.cnblogs.com/grandyang/p/4641968.html http://www.cnblogs.com/grandyang/p/4640572.html 利用二 ...

  2. 【LeetCode】236. Lowest Common Ancestor of a Binary Tree

    Lowest Common Ancestor of a Binary Tree Given a binary tree, find the lowest common ancestor (LCA) o ...

  3. Leetcode之236. Lowest Common Ancestor of a Binary Tree Medium

    236. Lowest Common Ancestor of a Binary Tree Medium https://leetcode.com/problems/lowest-common-ance ...

  4. 88 Lowest Common Ancestor of a Binary Tree

    原题网址:https://www.lintcode.com/problem/lowest-common-ancestor-of-a-binary-tree/description 描述 给定一棵二叉树 ...

  5. 【刷题-LeetCode】236. Lowest Common Ancestor of a Binary Tree

    Lowest Common Ancestor of a Binary Tree Given a binary tree, find the lowest common ancestor (LCA) o ...

  6. [LeetCode] 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 ...

  7. LeetCode Lowest Common Ancestor of a Binary Tree

    原题链接在这里:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ 题目: Given a binary tr ...

  8. [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 ...

  9. [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 ...

随机推荐

  1. 阿里云虚拟主机申请免费SSL证书并成功开通Https访问

    参考文档网址  https://baijiahao.baidu.com/s?id=1628343140232374972&wfr=spider&for=pc

  2. POJ3662 Telephone Lines (dijkstra+二分)

    Farmer John wants to set up a telephone line at his farm. Unfortunately, the phone company is uncoop ...

  3. Laravel Vuejs 实战:开发知乎 (1)项目环境配置和用户表设计

    1.使用laragon新建laravel项目 zhihu 2.配置env文件的database设置 DB_DATABASE=zhihu 3.分析users表需要的字段 4.修改数据库迁移文件: cla ...

  4. JSON 解析中遇到的坑😭

    最近做加解密遇到一个很“奇葩的问题”,解析服务端加密后的字符串 序列化 时一直报错 "json解析失败:Error Domain=NSCocoaErrorDomain Code=3840 & ...

  5. LoRa基础知识

    摘自:LoRaWAN介绍 - LoRa从业者读这篇就够了 https://blog.csdn.net/iotisan/article/details/69939241    LoRa网络结构      ...

  6. MYSQL优化考虑十个方面

    1)索引 2)sql优化 3)锁 4)延迟 5)参数优化 6)连接数 7)cpu 8)iops 9)磁盘 10)内存

  7. Linux 命令中 find 和 xargs 命令的用法

    find 命令(一) find 命令主要作用是沿着文件层次结构向下遍历,匹配符合条件的文件,并执行相应的操作.Linux 下 find 命令提供了相当多的查找条件,功能很强大,对应的学习难度也比较大. ...

  8. php 基础 PHP保留两位小数的几种方法

    $num = 10.4567; //第一种:利用round()对浮点数进行四舍五入 echo round($num,2); //10.46 //第二种:利用sprintf格式化字符串 $format_ ...

  9. solve License Key is legacy format when use ACTIVATION_CODE activate jetbrains-product 2019.3.1

    1.the java-agent and ACTIVATION_CODE can get from this site:https://zhile.io/2018/08/25/jetbrains-li ...

  10. vue学习笔记:vue的认识与特点与获取

    Vue了解 Vue:读作 view Vue是一个渐进式框架 与其他重量级框架不同的是,Vue 采用自底向上增量开发的设计. Vue 的核心库只关注视图层,并且非常容易学习,非常容易与其它库或已有项目整 ...