Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 12, 2017 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InterviewBytes/75e6c581b1a5bdf6f6f26e3e0462fd64 to your computer and use it in GitHub Desktop.
Save InterviewBytes/75e6c581b1a5bdf6f6f26e3e0462fd64 to your computer and use it in GitHub Desktop.
LCA Binary Tree
package com.interviewbytes.trees;
public class LowestCommonAncestorBinaryTree {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) return root;
if (left == null) return right;
return left;
}
}
package com.interviewbytes.trees;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment