forked from lizeyang18/byteDanceAlgorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest12.java
More file actions
38 lines (35 loc) · 1009 Bytes
/
test12.java
File metadata and controls
38 lines (35 loc) · 1009 Bytes
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
package byteDance;
/**
* Created by lizeyang on 2020/5/12.
* 二叉树的最近公共祖先
*/
public class test12 {
//O(n)
public static TreeNode test(TreeNode root,TreeNode p,TreeNode q){
if(root==null||root==p||root==q){
return root;
}
TreeNode left = test(root.left,p,q);
TreeNode right = test(root.right,p,q);
if(left!=null&&right!=null){
return root;
}
if(left==null){
return right;
}
if(right==null){
return left;
}
return null;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(5);
root.left = new TreeNode(4);
root.right = new TreeNode(8);
root.left.left = new TreeNode(3);
root.right.left = new TreeNode(7);
root.right.left.left = new TreeNode(6);
root.right.right = new TreeNode(9);
System.out.println(test(root,root.right,root.right.left).val);
}
}