Lowest Common Ancestor of a Binary Tree Solutions in Java
Number 236
Difficulty Medium
Acceptance 45.8%
Link LeetCode
Solutions
Java solution by haoel/leetcode
// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/// Inspired by : http://www.jiuzhang.com/solutions/lowest-common-ancestor/// Author : Lei Cao// Date : 2015-10-07package lowestCommonAncestorOfABinaryTree;import java.util.ArrayList;import java.util.Arrays;/*** 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 lowestCommonAncestorOfABinaryTree {/*** @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 || root == A || root == B) {return root;}TreeNode left = lowestCommonAncestor(root.left, A, B);TreeNode right = lowestCommonAncestor(root.right, A, B);if (left != null && right != null) {return root;}if (left != null) {return left;}if (right != null) {return right;}return null;}}