-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLCAOfBT.java
43 lines (40 loc) · 1.59 KB
/
LCAOfBT.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.
*/
public class LCAOfBT {
public static void main(String[] args) {
TreeNode root = new TreeNode(3);
root.left=new TreeNode(5);
root.right=new TreeNode(1);
root.left.left=new TreeNode(6);
root.left.right=new TreeNode(2);
root.right.left=new TreeNode(0);
root.right.right=new TreeNode(8);
root.left.left.left=null;
root.left.left.right=null;
root.right.right.left=new TreeNode(7);
root.right.right.right=new TreeNode(4);
TreeNode ans=lowestCommonAncestor(root, new TreeNode(5),new TreeNode(1));
System.out.println(ans.data);
}
public static 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 left;
}else{
return right;
}
}
}