Skip to content

Instantly share code, notes, and snippets.

@wszdwp
Created November 8, 2014 17:50
Show Gist options
  • Select an option

  • Save wszdwp/5e6560fd32cd728be064 to your computer and use it in GitHub Desktop.

Select an option

Save wszdwp/5e6560fd32cd728be064 to your computer and use it in GitHub Desktop.
LCA - Lowest common ancestor in a binary tree
//http://leetcode.com/2011/07/lowest-common-ancestor-of-a-binary-tree-part-i.html
public class LCA
{
public static TreeNode findTheLowestCommonAncestor(TreeNode root, TreeNode nd1, TreeNode nd2) {
if (root == null)
return null;
if (root == nd1 || root == nd2)
return root;
TreeNode left = findTheLowestCommonAncestor(root.left, nd1, nd2);
TreeNode right = findTheLowestCommonAncestor(root.right, nd1, nd2);
if (left != null && right != null)
return root;
else
return left == null ? right : left;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment