二叉树-Lowest Common Ancestor
来源:互联网 发布:禁止ip访问http linux 编辑:程序博客网 时间:2024/04/28 19:52
1. Binary search tree:只需要判断当前node值是否在两个node之间
2. Binary tree with parent link:先求两个node的height, 然后向上traverse
3. Binary tree without parent link:
solution 1: top-bottom
int countMatches(TreeNode root, TreeNode p, TreeNode q) {if (root == null) {return 0;}int matches = countMatches(root.left, p, q) + countMatches(root.right, p, q);if (root == p || root == q) {return matches + 1;} else {return matches;}}TreeNode findLCA(TreeNode root, TreeNode p, TreeNode q) {if (root == null || p == null || q == null) {return null;}int matches = countMatches(root, p, q);if (matches == 1) {return root;}if (matches == 2) {return findLCA(root.left, p, q);} else {return findLCA(root.right, p, q);}}
Solution 2: bottom-top
TreeNode findLCA2(TreeNode root, TreeNode p, TreeNode q) {if (root == null) {return null;}if (root == p || root == q) {return root;}TreeNode left = findLCA2(root.left, p, q);TreeNode right = findLCA2(root.right, p, q);if (left != null && right != null) { // 左边和右边分别含有p,qreturn root;}return left == null ? right : left;}
0 0
- 二叉树-Lowest Common Ancestor
- 二叉树系列4:lowest common ancestor
- 二叉树 之 lowest common ancestor 最低公共祖先
- codechef Lowest Common Ancestor
- Lowest Common Ancestor
- Lowest Common Ancestor
- Lowest common ancestor
- [刷题]Lowest Common Ancestor
- Lowest/first common ancestor
- Lowest Common Ancestor(LCA)
- Lowest Common Ancestor
- Lowest Common Ancestor
- Lowest Common Ancestor
- #88 Lowest Common Ancestor
- Lowest Common Ancestor III
- Lowest Common Ancestor II
- Lowest Common Ancestor III
- 【leetcode】二叉树的LCA问题:Lowest Common Ancestor of a Binary Tree
- 【转载】多态,虚函数,纯虚函数,抽象类
- 『ANDROID』Android实现圆形的图片边角
- C/C++中extern关键字详解
- Ext学习笔记01 - NameSpace,类实例属性,类实例方法,类静态方法
- JAVA常用容器结构的简单分析
- 二叉树-Lowest Common Ancestor
- 初入职场
- Python 3 会害死 Python
- 企业QQ SaaS团队,谈企业级LNMP架构设计
- 根据公司资源号得到部门,动态填入input框
- Android退出程序(一)——单例模式
- 5.2 单词查找树<正在更新>
- 例说Hausdorff距离
- 各种排序c语言实现