Skip to content

Commit 73ea26d

Browse files
committed
added LCA of Binary Tree
1 parent 18341e6 commit 73ea26d

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Trees/LCAofBinaryTree.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package Trees;
2+
3+
public class LCAofBinaryTree {
4+
5+
static class TreeNode {
6+
private int val;
7+
private TreeNode left,right;
8+
}
9+
10+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
11+
if(root.val == p.val || root.val == q.val) return root;
12+
13+
if(root.left == null && root.right == null) return null;
14+
15+
TreeNode left = null , right = null;
16+
17+
if(root.left != null)
18+
left = lowestCommonAncestor(root.left,p,q);
19+
if(root.right != null)
20+
right = lowestCommonAncestor(root.right,p,q);
21+
if(left != null && right != null)
22+
return root;
23+
24+
// if both p and q present in the right subtree
25+
return (left==null) ? right : left;
26+
}
27+
}

0 commit comments

Comments
 (0)