Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Create 236-Lowest-Common-Ancestor-of-a-Binary-Tree.java
Java language
  • Loading branch information
ArwaNayef authored Apr 8, 2022
commit 5f15b267d7e6ef6cda37ce3238edfa8dd582475c
14 changes: 14 additions & 0 deletions java/236-Lowest-Common-Ancestor-of-a-Binary-Tree.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null) return null;
if((root.val==p.val || root.val==q.val))return root;
TreeNode left=lowestCommonAncestor(root.left,p,q);
TreeNode right=lowestCommonAncestor(root.right,p,q);

if(left!=null&&right!=null){return root;}
else if(left!=null)return left;
else return right;

}

}