首页 > 代码库 > Lowest Common Ancestor III Lintcode
Lowest Common Ancestor III Lintcode
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.
Return null
if LCA does not exist.
Notice
node A or node B may not exist in tree.
Have you met this question in a real interview?
Yes
Example
For the following binary tree:
4
/ 3 7
/ 5 6
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
这道题做得累死了。。。主要的点在于变换递归的位置,就会造成不同的后果,如果放在一开始,那么就会一直到null才停止递归。。。这道题是从下向上。而且要想到可以新建一个类。什么时候要新建什么时候不用目前还没有太掌握。。。另外class不要写public的,不然要单独放在名为class名的文件里。
class Result { boolean foundA; boolean foundB; TreeNode root; public Result(boolean a, boolean b, TreeNode root) { foundA = a; foundB = b; this.root = root; } } public class Solution { /** * @param root The root of the binary tree. * @param A and B two nodes * @return: Return the LCA of the two nodes. */ public TreeNode lowestCommonAncestor3(TreeNode root, TreeNode A, TreeNode B) { Result rs = helper(root, A, B); if (rs.foundA && rs.foundB) { return rs.root; } return null; } public Result helper(TreeNode root, TreeNode A, TreeNode B) { if (root == null) { return new Result(false, false, null); } Result left = helper(root.left, A, B); Result right = helper(root.right, A, B); boolean a = left.foundA || right.foundA || root == A; boolean b = left.foundB || right.foundB || root == B; if (root == A || root == B) { return new Result(a, b, root); } if (left.root != null && right.root != null) { return new Result(a, b, root); } if (left.root != null) { return new Result(a, b, left.root); } if (right.root != null) { return new Result(a, b, right.root); } return new Result(a, b, null); } }
需要回顾。。。
Lowest Common Ancestor III Lintcode
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。