Lowest Common Ancestor III Lintcode
Posted 璨璨要好好学习
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
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的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 236. Lowest Common Ancestor of a Binary Tree; 235. Lowest Common Ancestor of a Binary Searc