Repository navigation
Expand file tree
/
Copy pathlowestCommonAncestor236.java
More file actions
75 lines (66 loc) · 2.1 KB
/
Copy pathlowestCommonAncestor236.java
File metadata and controls
75 lines (66 loc) · 2.1 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package tencent50;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class lowestCommonAncestor236 {
private TreeNode ans;
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public static void main(String[] args){
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
this.choose(root, p, q);
return this.ans;
/*if(root == null) return null;
Queue<TreeNode> stack = new LinkedList<>();
stack.add(root);
boolean pchange = false;
boolean qchange = false;
while(p.val != q.val){
if(pchange && qchange) {
pchange = false;
qchange = false;
stack.clear();
stack.add(root);
}
if(stack.isEmpty()) return null;
else root = stack.poll();
if(root.left != null) {
if (root.left == p || root.left == q) {
if (root.left == p) {
p = root;
pchange = true;
} else{
q = root;
qchange = true;
}
} else stack.add(root.left);
}
if(root.right != null) {
if (root.right == p || root.right == q) {
if (root.right == p){
p = root;
pchange = true;
}
else {
q = root;
qchange = true;
}
} else stack.add(root.right);
}
}
return p;*/
}
public boolean choose(TreeNode currentNode, TreeNode p, TreeNode q) {
if(currentNode == null) return false;
int left = this.choose(currentNode.left, p, q)? 1 : 0;
int right = this.choose(currentNode.right, p, q)? 1 : 0;
int mid = (currentNode == p || currentNode == q)? 1 : 0;
if((left + right + mid) >= 2) this.ans = currentNode;
return (left + right + mid) > 0;
}
}