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. nmon监控与 nmon analyser分析

    参考 https://www.cnblogs.com/wnfindbug/p/5719181.html 1.下载 nmon https://zh.osdn.net/projects/sfnet_nmo ...

  2. ios 审核未通过 相机相册权限问题

    苹果提交审核被打回来  附加的说明如下: We noticed that your app requests the user’s consent to access their camera but ...

  3. 使用element-ui 遇到的问题

    Pagination 分页 在使用分页的时候,每次切换pageSize的时候,需要把current-page置为1 重新加载数据. 但是当current-page !== 1的时候,修改current ...

  4. Git常用指令和GitHub操作总结

    Git版本管理工具(CVS) 首先粘上两个Git的基础链接~ 阮一峰:http://www.ruanyifeng.com/blog/2015/12/git-cheat-sheet.html 廖雪峰:h ...

  5. VS Code + NWJS(Node-Webkit)0.14.7 + SQLite3 + Angular6 构建跨平台桌面应用

    一.项目需求 最近公司有终端桌面系统需求,需要支持本地离线运行(本地数据为主,云端数据同步),同时支持Window XP,最好跨平台.要求安装配置简单(一次性打包安装),安装包要小,安装时间短,可离线 ...

  6. 类Shiro权限校验框架的设计和实现(2)--对复杂权限表达式的支持

    前言: 我看了下shiro好像默认不支持复杂表达式的权限校验, 它需要开发者自己去做些功能扩展的工作. 针对这个问题, 同时也会为了弥补上一篇文章提到的支持复杂表示需求, 特地尝试写一下解决方法. 本 ...

  7. ggplot2 multiply graphs on one figure

    library(ggplot2)library(grid)grid.newpage()pushViewport(viewport(layout = grid.layout(1,2)))vplayout ...

  8. Python全栈之路----常用模块----datetime模块详解

    相比于time模块,datetime模块的接口则更直观,更容易调用. datetime模块定义了下面这几个类: datetime.date:表示日期的类,常用的属性有year,month,day: d ...

  9. Redis占硬盘空间

    转载自:http://blog.csdn.net/qq285744011/article/details/51002409 [问题的原因] Windows版Redis启动后,会在C盘自动创建一个很大的 ...

  10. CodeForces - 455D

    Serega loves fun. However, everyone has fun in the unique manner. Serega has fun by solving query pr ...