-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLowestCommonAncestor.java
More file actions
42 lines (37 loc) · 1.11 KB
/
Copy pathLowestCommonAncestor.java
File metadata and controls
42 lines (37 loc) · 1.11 KB
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
package tree;
import org.junit.Test;
/**
* @Author: wei1
* @Date: Create in 2019/2/2 20:05
* @Description: 最近公共父节点
*/
public class LowestCommonAncestor {
@Test
public void test() {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
TreeNode six = new TreeNode(6);
root.right.left = six;
TreeNode p = new TreeNode(4);
TreeNode q = new TreeNode(5);
root.left.left = p;
root.left.right = q;
TreeNode treeNode = lowestCommonAncestor(root, p, six);
System.out.println(treeNode.val);
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root.val == p.val || root.val == q.val) {
return root;
}
TreeNode leftN = lowestCommonAncestor(root.left, p, q);
TreeNode rightN = lowestCommonAncestor(root.right, p, q);
if (leftN != null && rightN != null) {
return root;
}
if (leftN == null) {
return rightN;
}
return leftN;
}
}