Lowest Common Ancestor III
Analysis:
1) 左子树是不是有LCA(A,B)
2) 右子树是不是有LCA(A,B)
==>
A. 有 返回LCA(A,B)
B. 没有
==>
b1) 如果有遇到A或者B, 返回A或B
b2)没有遇到返回null
注意;要判断AB有没有遇到。
/** * 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 tree. * @param A and B two nodes * @return: Return the LCA of the two nodes. */ private class RstType { TreeNode node; boolean isAExist; boolean isBExist; public RstType (TreeNode node, boolean isAExist, boolean isBExist) { this.node = node; this.isAExist = isAExist; this.isBExist = isBExist; } } public TreeNode lowestCommonAncestor3(TreeNode root, TreeNode A, TreeNode B) { // write your code here RstType rst = helper(root, A, B); if (rst.isAExist && rst.isBExist) { return rst.node; } else { return null; } } RstType helper(TreeNode root, TreeNode A, TreeNode B) { if (root == null) { return new RstType(null, false, false); } RstType left = helper(root.left, A, B); RstType right = helper(root.right, A, B); boolean isAExist = left.isAExist || right.isAExist || root == A; boolean isBExist = left.isBExist || right.isBExist || root == B; if (root == A || root == B) { return new RstType(root, isAExist, isBExist); } if (left.node != null && right.node != null) { return new RstType(root, isAExist, isBExist); } else if (left.node != null) { return new RstType(left.node, isAExist, isBExist); //因为右子树为空,所以LCA(左右)就是LCA(左) } else if (right.node != null) { return new RstType(right.node, isAExist, isBExist); } else { return new RstType(null, isAExist, isBExist); } //System.out.println(root.val); } }
posted on 2017-03-15 07:24 codingEskimo 阅读(117) 评论(0) 收藏 举报
浙公网安备 33010602011771号