-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathlca.cpp
More file actions
33 lines (29 loc) · 982 Bytes
/
lca.cpp
File metadata and controls
33 lines (29 loc) · 982 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
// http://leetcode.com/2011/07/lowest-common-ancestor-of-a-binary-tree-part-i.html
#include "leetcode.h"
// cases to consider:
// 1. p or q == root: LCA is root
// 2. p and q in different sides of root: LCA is root
class Solution {
public:
int count = 0;
TreeNode *LCA(TreeNode *root, TreeNode *p, TreeNode *q) {
++count;
if (root == nullptr) return nullptr;
if (root == p || root == q) return root; // root is in the path
TreeNode *L = LCA(root->left, p, q);
TreeNode *R = LCA(root->right, p, q);
if (L && R) return root; // p, q at both sides
return L? L : R; // p, q at either side, or not found
}
};
int main() {
Solution sol;
TreeNode *root = deserialize_tree(string("1 2 4 # # 5 # # 3 # #"));
TreeNode *p = root->left->left;
// TreeNode *q = root->right;
// TreeNode *q = root->left->right;
TreeNode *q = root->left;
TreeNode *lca = sol.LCA(root, p, q);
cout << lca->val << " count: " << sol.count << "\n";
return 0;
}