class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == NULL || root == p || root == q)
{
return root;
}
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left && right)
{
return root;
}
else
{
return left == NULL ? right : left;
}
}
};

补充一个DFS实现,使用先序遍历将每一个路径都记录下来,然后分情况讨论。

 public class Solution
{
List<List<TreeNode>> V = new List<List<TreeNode>>();
Stack<TreeNode> v = new Stack<TreeNode>(); public void PostTree(TreeNode node)
{
if (node != null)
{
v.Push(node);
if (node.left != null)
{
PostTree(node.left);
v.Pop();
}
if (node.right != null)
{
PostTree(node.right);
v.Pop();
}
if (node.left == null && node.right == null)
{
var list = new List<TreeNode>();
foreach (var s in v)
{
list.Add(s);
}
list.Reverse();
V.Add(list);
} }
} public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
{
PostTree(root);
int p_index = -;
int q_index = -;
for (var i = ; i < V.Count(); i++)
{
if (V[i].Find(x => x.val == p.val) != null)
{
p_index = i;
}
if (V[i].Find(x => x.val == q.val) != null)
{
q_index = i;
}
if (p_index >= && q_index >= )
{
break;
}
}
if (p_index == q_index)
{
var l = V[p_index];
//p和q在同一个路径上
foreach (var va in l)
{
if (va.val == p.val || va.val == q.val)
{
return va;
}
}
}
else
{
//p和q在不通路径上
var l1 = V[p_index];
var l2 = V[q_index];
int i = ;
int j = ;
while (i < l1.Count() && j < l2.Count())
{
if (l1[i].val != l2[j].val)
{
return l1[i - ];
}
i++;
j++;
}
}
return null;
}
}

补充一个python的实现:

 class Solution:
#当p和q分别在某节点的左子树和右子树的时候,这个节点就是LCA
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root == None or root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left,p,q)#在左子树中找p或q
right = self.lowestCommonAncestor(root.right,p,q)#在右子树中找p或q
if left != None and right != None:#p和q分别在这个节点的左右子树,则当前节点就是LCA
return root
elif left != None:#p和q都在这个节点的左子树,则在p和q中,先被找到的就是LCA
return left
elif right != None:#p和q都在这个节点的右子树,则先被找到的就是LCA
return right
else:
return None#p和q不在这个节点的子树中

LCA让我想起了日月生辉的光辉战斗机。

leetcode236的更多相关文章

  1. [Swift]LeetCode236. 二叉树的最近公共祖先 | 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 ...

  2. 面试题6:二叉树最近公共节点(LCA)《leetcode236》

    Lowest Common Ancestor of a Binary Tree(二叉树的最近公共父亲节点) Given a binary tree, find the lowest common an ...

  3. LeetCode236. 二叉树的最近公共祖先

    * @lc app=leetcode.cn id=236 lang=cpp  *  * [236] 二叉树的最近公共祖先  *  * https://leetcode-cn.com/problems/ ...

  4. 奇安信集团笔试题:二叉树的最近公共祖先(leetcode236),杀死进程(leetcode582)

    1. 二叉树最近公共祖先     奇安信集团 2020校招 服务端开发-应用开发方向在线考试 编程题|20分2/2 寻祖问宗 时间限制:C/C++语言 1000MS:其他语言 3000MS 内存限制: ...

  5. leetcode236 Lowest Common Ancestor of a Binary Tree

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

  6. leetcode探索高级算法

    C++版 数组和字符串 正文 链表: 正文 树与图: 树: leetcode236. 二叉树的最近公共祖先 递归(先序) leetcode124二叉树最大路径和 递归 图: leetcode 547朋 ...

  7. leetcode_二叉树篇_python

    主要是深度遍历和层序遍历的递归和迭代写法. 另外注意:因为求深度可以从上到下去查 所以需要前序遍历(中左右),而高度只能从下到上去查,所以只能后序遍历(左右中). 所有题目首先考虑root否是空.有的 ...

  8. LeetCode通关:连刷三十九道二叉树,刷疯了!

    分门别类刷算法,坚持,进步! 刷题路线参考:https://github.com/youngyangyang04/leetcode-master 大家好,我是拿输出博客来督促自己刷题的老三,这一节我们 ...

随机推荐

  1. 网页全屏,modal 弹框无法显示的问题

    问题描述页面主体部分全屏后,页面中的所有弹窗不能显示,退出全屏后,弹窗正常.解决方法校园项目中,所有用到的弹窗为iview的弹窗组件,该弹窗组件会生成在body中,和项目主体app为平行关系,项目主体 ...

  2. MYSQL数据模型

    DROP TABLE IF EXISTS `sh_category`; CREATE TABLE `sh_category` ( `id` int(11) NOT NULL AUTO_INCREMEN ...

  3. linux (centOS)安装jdk+tomcat+nginx

    一..安装jdk, 下载jdk有两种方式: 1.直接去官网找相应版本下载:http://www.oracle.com/technetwork/java/javase/downloads/index.h ...

  4. emmet简单记录

    一.引式符号 html:5 or  ! . class #  id []标签内属性 pycharm不支持  {}标签的内容 pycharm不支持 ()分组标签  pycharm不支持 二.关系符号 1 ...

  5. openssl查看apk的证书信息

    查看apk的证书信息: openssl pkcs7 -inform DER -in CERT.RSA -noout -print_certs -text

  6. InstallShield-常用prq文件的下载地址

    VC 2010 redist X86: http://saturn.installshield.com/is/prerequisites/microsoft visual c++ 2010 redis ...

  7. Gym101889E. Enigma(bfs+数位)

    比赛链接:传送门 题目大意: 求一个十进制大数S(有部分数位为"?")能被N整除时的最小值,如果没有办法被N整除,输出"*". 思路: 一个数位上的数值增加1后 ...

  8. https加载非https资源时不出现问题

    老规矩,国服第一博客copy王,原文链接:https://blog.csdn.net/zhengbingmei/article/details/81325325将系统变成了https访问之后,发现部分 ...

  9. 使用Blend设计出符合效果的WPF界面

    之前不会用blend,感觉好难的,但美工给出的效果自己有没办法实现,所以研究了一下blend,感觉没有想象中的那么难 废话不多说,开始界面设计 今天拿到美工给的一个界面效果图 这个界面说实话,还可以吧 ...

  10. H5入门须知

    ---恢复内容开始--- 首先,让我们来了解一下H5是做什么的,H5全称为“超文本标记语言”.是对网页进行编辑的技术.H5运用Hbulider进行网页编辑.网页可以分为三部分分别是title(主题)u ...