LintCode:M-最近祖先
来源:互联网 发布:怎么修改淘宝评论 编辑:程序博客网 时间:2024/06/10 00:47
LinCode链接
给定一棵二叉树,找到两个节点的最近公共父节点(LCA)。
最近公共祖先是两个节点的公共的祖先节点且具有最大深度。
注意事项
假设给出的两个节点都在树中存在
样例
对于下面这棵二叉树
4 / \3 7 / \ 5 6
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */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) { // write your code here return findNode(root, A, B); } TreeNode findNode(TreeNode root, TreeNode A, TreeNode B){ if(root == null) return null; //找到了目标node,返回目标 if(root.val == A.val) return root; if(root.val == B.val) return root; TreeNode left = findNode(root.left, A, B); TreeNode right = findNode(root.right, A, B); if(left!=null && right!=null)//左右两边都找到了目标,则该节点是最近LCA return root; return left!=null?left:right; }}
阅读全文
0 0
- LintCode:M-最近祖先
- LintCode-最近公共祖先
- LintCode 最近公共祖先
- LintCode:最近公共祖先
- LintCode:最近公共祖先
- lintcode-最近公共祖先
- 最近公共祖先,lintcode
- lintcode, 最近公共祖先
- 最近公共祖先-LintCode
- lintcode--最近公共祖先
- lintcode----最近公共祖先
- lintcode-最近公共祖先-88
- [LintCode]88.最近公共祖先
- LintCode-剑指Offer-(88)最近公共祖先
- lintcode lowest-common-ancestor 最近公共祖先
- [Lintcode]Lowest Common Ancestor 最近公共祖先
- LintCode:M-K个最近的点
- LintCode(M)
- 高级ROP
- greenplum导出表、数据、模式的sql
- Effective Jave 创建和销毁对象 4.通过私有构造器强化不可实例化的能力
- Morris Traversal方法遍历二叉树(非递归,不用栈,O(1)空间)
- break,continue,return的区别
- LintCode:M-最近祖先
- 使用Photoshop给Premiere批量添加对白字幕听语音 |浏览:25974|更新:2013-12-23 23:18|标签:photoshop premiere 使用Photoshop给Pre
- ajax 实现文件下载功能
- adb使用-详细教程(Awesome Adb)
- PAT --- 1006. 换个格式输出整数 (15)
- 【Redis源码剖析】
- View[3] scrollTo、scrollBy
- window.location实用知识
- map(multimap)与pair