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. 下载EU台网(欧洲台网)的地震波数据

    retrievedata.py ### here first to check the existence of the focal mechanism event file in the NDK d ...

  2. 18-10-09 Linux常用命令大全(非常全!!!)

     Linux常用命令大全(非常全!!!)   Linux常用命令大全(非常全!!!) 最近都在和Linux打交道,感觉还不错.我觉得Linux相比windows比较麻烦的就是很多东西都要用命令来控制, ...

  3. 通过pid杀死进程

    bool ****::KillProcess(DWORD pid) { // When the all operation fail this function terminate the " ...

  4. Redis配置文件 redis.conf 解读(一)

    # Redis configuration file example# redis配置文件模板# Note on units: when memory size is needed, it is po ...

  5. Xcode 和 VisualC++输出流的差别的理解

    将这样一段程序分别运行与Visual Studio 和 Xcode上边的结果: #include <iostream> using namespace std; int main() { ...

  6. linux ---> taskkill pid 8080 /f

    ★ :--linux->-端口占用 : netstat -anonetstat -ano|findstr 8003taskkill /pid 4816 /f

  7. 一 Struts框架(上)

    Struts2 是基于MVC的WEB框架 经过六年多的发展,Struts1已经成为了一个高度成熟的框架,不管是稳定性还是可靠性都得到了广泛的证明.市场占有率超过20%,拥有丰富的开发人群,几乎已经成为 ...

  8. bootstrap弹出模态框会给body加padding的解决方法

    bootstrap弹出模态框会给body加padding,导致页面缩放的解决方法: 在页面或是css文件里加上($paddingSize为less变量,需要改成像素或是其他单位,如12px,1rem) ...

  9. Hanlp汉字转拼音使用python调用详解

    1.hanlp简介 HanLP是一系列模型与算法组成的NLP工具包,由大快搜索主导并完全开源,目标是普及自然语言处理在生产环境中的应用.HanLP具备功能完善.性能高效.架构清晰.语料时新.可自定义的 ...

  10. [转]Linux下Python与C++混合编程

    转自:http://www.cnblogs.com/tevic/p/3645197.html 最近在做一个CUDA的项目,记录下学习心得. 系统 Linux 3.11.0-19-generic #33 ...