0%

1650. Lowest Common Ancestor of a Binary Tree III

O(h) time O(1) space
160. Intersection of Two Linked Lists一样

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node* parent;
};
*/

class Solution {
public:
Node* lowestCommonAncestor(Node* p, Node * q) {
auto a = p, b = q;
while (a != b) {
a = a ? a->parent : q;
b = b ? b->parent : p;
}
return a;
}
};