"""
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. windows与linux的文件路径

    在windows操作系统中,文件路径的分隔符是反斜杠(“\\”),例如: E:\\hsta\\pdf(这里为防止转义,所以要写成两个反斜杠) 但是在linux操作系统中,文件的分隔符是斜杠(“/”), ...

  2. css不起作用报错:Resource interpreted as Stylesheet but transferred with MIME type text/html

    解决:https://blog.csdn.net/sky_cui/article/details/86703706 找了好久........

  3. [Write-up]-Trollcave: 1.2

    关于 下载地址:点我 Flag:root/flag.txt 哔哩哔哩:视频 信息收集 不知道VM虚拟机怎么啦,导入镜像后,用Nmap扫了,发现不了主机.所以这次用了VBox. vboxnet0的IP为 ...

  4. 怎么修改Anaconda 中 jupyter notebook 文件的保存位置

    安装完 anaconda ,在jupyter notebook 中创建的文件的默认保存位置为C:\User\电脑名 修改保存位置 1.打开 anaconda prompt 2.输入 jupyter n ...

  5. win10常用快捷键总结

    前言: 很多快捷键在不同版本系统基本相同的,但是今天推送的这篇文章更多的介绍 win10快捷键,微软也是大力推广 旗舰系统 win10 ,所以大家提前升级,提前学习还是有必要的.毕竟2020年微软会放 ...

  6. ubuntu13.10安装tomcat

    步骤: ubuntu :13.10(32bit) -->i586 jdk 1.7 安装JDK 步骤: 1.官网下载如下图: 2.点击java SE7,下载jdk1.7 3.点击接受,并下载对应的 ...

  7. 企业面试问题收集-ssm框架

    springMVC 1)    简单介绍下你对springMVC的理解? Spring MVC Framework有这样一些特点: 1.它是基于组件技术的.全部的应用对象,无论控制器和视图,还是业务对 ...

  8. 关于eclipse项目右键没有project facets的解决方法遇到的问题

    [ 关于eclipse项目右键没有project facets的解决方法] [创建maven项目生成WebRoot目录,web.xml文件,以及修改编译路径classess的解决办法,以及解决找不到或 ...

  9. Linux centosVMware PHP动态扩展模块

    PHP动态扩展模块 /usr/local/php/bin/php -m //查看模块 下面安装一个redis的模块 cd /usr/local/src/ wget https://codeload.g ...

  10. axios发送post请求[body-parser]--['Content-type': 'application/x-www-form-urlencoded']

    const express = require('express') const axios = require('axios') const bodyParser = require('body-p ...