We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 18341e6 commit 73ea26dCopy full SHA for 73ea26d
Trees/LCAofBinaryTree.java
@@ -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