0%

1644. Lowest Common Ancestor of a Binary Tree II

236. Lowest Common Ancestor of a Binary Tree的followup
postorder O(n) time O(h) space

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
auto res = lca(root, p, q);
return cnt == 2 ? res : nullptr;
}

TreeNode *lca(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root) return root;
auto l = lca(root->left, p, q);
auto r = lca(root->right, p, q);
if (root == p || root == q) {
++cnt;
return root;
}
if (l && r) return root;
return l ? l : r;
}

int cnt = 0;
};
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
auto res = lca(root, p, q);
return cnt == 2 ? res : nullptr;
}

TreeNode *lca(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root) return root;
if (root == p || root == q) {
if (++cnt == 2) return root;
}
auto l = lca(root->left, p, q);
auto r = lca(root->right, p, q);
if (cnt == 1) return root;
if (l && r) return root;
if (cnt == 2) return (root == p || root == q) ? root : (l ? l : r);
return nullptr;
}

int cnt = 0;
};