leetcode面试准备:Lowest Common Ancestor of a Binary Search Tree & Binary Tree
leetcode面试准备:Lowest Common Ancestor of a Binary Search Tree & Binary Tree
1 题目
Binary Search Tree的LCA
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
接口: TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
Binary Tree的LCA
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 v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______3______
/ \
___5__ ___1__
/ \ / \
6 _2 0 8
/ \
7 4
For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
接口: TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
2 思路
在二叉树数中寻找两个节点的最低公共父节点。更容易一点的题目是限定在搜索二叉树中。
搜索二叉树:左子树 < root < 右子树,即中序遍历有序。
思路1
遍历2次,找到节点p
、q
的路径,然后在遍历1次两条路径,找到公共的最低节点。这个节点是所求的。
- 搜索二叉树:利用BST性质,判断节点值的大小,很容易找到节点的路径。
- 一般二叉树:DFS找公共节点
复杂度: 遍历3次,用了额外的储存空间。如何分析树的时间和空间复杂度?
思路2
树的结构,很容易想到递归。LCA要么在root上,要么在左右子树中。
- 搜索二叉树
根据BST的性质,两个节点p,q的公共袓先root, 一定满足p <= root <= q 或者 p >= root >= q。
使用递归可以轻松解决此问题。分为三种情况讨论:
- P, Q都比root小,则LCA在左树,我们继续在左树中寻找LCA
- P, Q都比root大,则LCA在右树,我们继续在右树中寻找LCA
- 其它情况,表示P,Q在root两边,或者二者其一是root,或者都是root,这些情况表示root就是LCA,直接返回root即可。
- 一般二叉树
The idea is to traverse the tree starting from root. 具体见代码实现吧。
- If any of the given keys (n1 and n2) matches with root, then root is LCA (assuming that both keys are present).
- If root doesn’t match with any of the keys, we recur for left and right subtree. The node which has one key present in its left subtree and the other key present in right subtree is the LCA.
- If both keys lie in left subtree, then left subtree has LCA also, otherwise LCA lies in right subtree.
3 代码
BST的LCA
只写了思路2的代码
// 递归
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null)
return root;
final int value = root.val;
if (Math.max(p.val, q.val) < value)
return lowestCommonAncestor(root.left, p, q);
if (Math.min(p.val, q.val) > value)
return lowestCommonAncestor(root.right, p, q);
return root;
}
// 迭代做法
public TreeNode lca(TreeNode root, TreeNode p, TreeNode q) {
TreeNode cur = root;
for (;;) {
int value = cur.val;
if (p.val < value && q.val < value)
cur = cur.left;
else if (p.val > value && q.val > value)
cur = cur.right;
else
return cur;
}
}
BT的LCA
思路2的代码
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
// If the root is one of a or b, then it is the LCA
if (root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
// If both nodes lie in left or right then their LCA is in left or right,
// Otherwise root is their LCA
if (left != null && right != null) {
return root;
}
return (left != null) ? left : right;
}
思路1的代码
public TreeNode lca(TreeNode root, TreeNode p, TreeNode q) {
Deque<TreeNode> pPath = new LinkedList<TreeNode>();
Deque<TreeNode> qPath = new LinkedList<TreeNode>();
findPath(root, p, pPath);
findPath(root, q, qPath);
TreeNode prev = null;
for (; !pPath.isEmpty() && !qPath.isEmpty();) {
TreeNode parent = pPath.removeFirst();
if (parent == qPath.removeFirst()) {
prev = parent;
} else {
break;
}
}
return prev;
}
/**
* DFS 寻找路径
*/
private boolean findPath(TreeNode root, TreeNode node, Deque<TreeNode> path) {
if (root == null)
return false;
if (root == node) {
path.addLast(root);
return true;
}
path.addLast(root);
if (findPath(root.left, node, path))
return true;
if (findPath(root.right, node, path))
return true;
path.removeLast();
return false;
}
4 总结
树的题目,不熟悉,多总结一下吧。
5 参考
leetcode面试准备:Lowest Common Ancestor of a Binary Search Tree & Binary Tree的更多相关文章
- 【LeetCode】236. Lowest Common Ancestor of a Binary Tree 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...
- 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 ...
- 【一天一道LeetCode】#235. Lowest Common Ancestor of a Binary Search Tree
一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...
- 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree 解题报告(Java & Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 [LeetCode] https://leet ...
- LeetCode 【235. Lowest Common Ancestor of a Binary Search Tree】
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...
- 【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 ...
- 【LeetCode 235】Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...
- LeetCode OJ 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 ...
- LeetCode OJ 235. Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...
随机推荐
- ionic(一) build你的第一个android apk
1.ionic start myApp tabs >>创建一个app 2.cd myApp >>进入myApp文件 3.ionic platform add andro ...
- SecurityException:Not allowed to start service Intent ,without permission not exported from
本来是学长以前的项目,我正在重做一遍.结果突然出现了异常,我很是不解啊,怎么莫名其妙的就出现异常了呢?我昨天用还是好好的,根本就没动过源代码.于是在网上开始了一遍又一遍的查询,有的说要加权限.有的说这 ...
- Ubuntu12.04 下安装Qt
1.下载Qt Creator 链接 http://qt-project.org/downloads 选择 Qt Creator 2.8.0 for Linux/X11 32-bit (61 MB) ...
- Solr使用初探——SolrJ的使用
二.SolrJ的使用 SolrJ覆盖了solr的全部功能,下面将自己在实际开发中所使用的程序粘贴出来并适当加以解释,由于本人比较菜,代码书写不是那么的精练,还请见谅. 1. 创建solrserver ...
- jjQuery 源码分析1: 整体结构
目前阅读的是jQuery 1.11.3的源码,有参考nuysoft的资料. 原来比较喜欢在自己的Evernote上做学习基类,并没有在网上写技术博客的习惯,现在开始学习JS的开源代码,想跟大家多交流, ...
- bzoj1131: [POI2008]Sta
思路:首先先求出以1为根的答案,然后考虑由i转移到i的儿子的答案的变化,显然以son[i]为根的子树的所有结点的深度都会减一,其余的点的深度都会加一,然后就可以直接O(n)求出所有结点的答案,然后取m ...
- ios 64位下编译webrtc的libvpx库出现错误Bad cputype for object file.Currently only tested for CPU_TYPE_x86_64
diff --git a/libvpx.gyp b/libvpx.gypindex 4f8cb2b..4eb6866 100644--- a/libvpx.gyp+++ b/libvpx.gyp@@ ...
- .net ajax式上传文件
今天在这里介绍一下ajax上传文件.其实也不算是真的使用xmlhttprequest上传,只是使用了iframe实现了无刷新上传而已,最多也只算 是仿ajax上传文件.然而网上关于使用xmlhttpr ...
- js+jquery检测用户浏览器型号(包括对360浏览器的检测)
做网站,js检测用户浏览器的版本,是经常要使用到,今天自己写了一个js,完成了对于一些常见浏览器的检测,但是,偏偏对于360浏览器的检测没有任 何办法,研究了一会儿,无果.无论是360安全浏览器,还是 ...
- 缓存 Cache
Controllers层 public class HomeController : Controller { // // GET: /Home/ // ...