**Lowest Common Ancestor of Two Nodes in a Binary Tree
2015-08-31 00:59
435 查看
Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.
The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.
Example
For the following binary tree:
LCA(3, 5) =
LCA(5, 6) =
LCA(6, 7) =
解法一:
解法二:分治法
reference:http://ryanleetcode.blogspot.com/2015/04/lowest-common-ancestor.html
The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.
Example
For the following binary tree:
4 / \ 3 7 / \ 5 6
LCA(3, 5) =
4
LCA(5, 6) =
7
LCA(6, 7) =
7
解法一:
/** * 本代码由九章算法编辑提供。没有版权欢迎转发。 * - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。 * - 现有的面试培训课程包括:九章算法班,系统设计班,BAT国内班 * - 更多详情请见官方网站:http://www.jiuzhang.com/ */ Version 1: Traditional Method public class Solution { private ArrayList<TreeNode> getPath2Root(TreeNode node) { ArrayList<TreeNode> list = new ArrayList<TreeNode>(); while (node != null) { list.add(node); node = node.parent; } return list; } public TreeNode lowestCommonAncestor(TreeNode node1, TreeNode node2) { ArrayList<TreeNode> list1 = getPath2Root(node1); ArrayList<TreeNode> list2 = getPath2Root(node2); int i, j; for (i = list1.size() - 1, j = list2.size() - 1; i >= 0 && j >= 0; i--, j--) { if (list1.get(i) != list2.get(j)) { return list1.get(i).parent; } } return list1.get(i+1); } }
解法二:分治法
public class Solution { /** * @param root: The root of the binary search tree. * @param A and B: two nodes in a Binary. * @return: Return the least common ancestor(LCA) of the two nodes. */ public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) { if (root == null){ return null; } if (root == A || root == B){ return root;//当找到一中一个node, 向上传递这个node } TreeNode left = lowestCommonAncestor(root.left, A, B); TreeNode right = lowestCommonAncestor(root.right, A, B); if (left != null && right != null){//check左右,如果左右分别包含两个node则这个root就是LCA, 向上传递这个node return root; } else if (left != null){//只有左边有node,向上传递此node return left; } else if (right != null){ return right; } else{//左右边都没有node 传递null return null; } } }
reference:http://ryanleetcode.blogspot.com/2015/04/lowest-common-ancestor.html
相关文章推荐
- 安装supervisor调试nodejs
- 安装node-inspector来调试node
- Node.js socketio一对一客服系统
- 深入理解磁盘文件系统之inode
- net平台webservice跨域调用以及node调用webservice
- Count Complete Tree Nodes
- Swap Nodes in Pairs
- LeetCode-Count Complete Tree Nodes
- nodejs处理get请求
- 一步一步讲解安装NodeJs开发环境
- Nodejs初阶之express
- leetcode_019Remove Nth Node From End of List
- btrfs连载(一)inode.c之btrfs_create函数
- LeetCode Swap Nodes in Pairs
- LeetCode Swap Nodes in Pairs
- 2015-08-04个人定制(nodejs中的循环陷阱)
- HDFS架构——NameNode
- 25 Reverse Nodes in k-Group
- Leetcode 222: Count Complete Tree Nodes
- Delete Node in a Linked List 单链表删除节点