-
-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
Copy path236.c
82 lines (65 loc) · 2.02 KB
/
236.c
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
76
77
78
79
80
81
82
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
// The list for TreeNodes.
struct ListItem {
struct TreeNode* node; // TreeNode pointer
struct ListItem* next; // Pointer to the next ListItem
};
bool findTargetPath(struct TreeNode* node, struct TreeNode* target, struct ListItem* path){
if (node == NULL){
return false;
}
struct ListItem* pathItem = malloc(sizeof(struct ListItem));
pathItem->node = node;
pathItem->next = NULL;
path->next = pathItem;
if (node->val == target->val){
return true;
}
if (findTargetPath(node->left, target, pathItem)){
return true;
}
if (findTargetPath(node->right, target, pathItem)){
return true;
}
path->next = NULL;
free(pathItem);
return false;
}
void freeList(struct ListItem* target){
if (target->next != NULL){
freeList(target->next);
}
free(target);
}
// Find full path for p and q.
// Find the longest common path in paths.
// Runtime: O(n)
// Space: O(n)
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
struct ListItem* pPath = malloc(sizeof(struct ListItem));
struct ListItem* qPath = malloc(sizeof(struct ListItem));
findTargetPath(root, p, pPath);
findTargetPath(root, q, qPath);
struct TreeNode* lowestTreeNode = NULL;
struct ListItem* pPathCursor = pPath->next;
struct ListItem* qPathCursor = qPath->next;
while(pPathCursor != NULL && qPathCursor != NULL) {
if (pPathCursor->node->val == qPathCursor->node->val){
lowestTreeNode = pPathCursor->node;
pPathCursor = pPathCursor->next;
qPathCursor = qPathCursor->next;
continue;
}
break;
}
freeList(pPath);
freeList(qPath);
return lowestTreeNode;
}