二叉树的最近公共祖先

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
/**
* Definition for a binary tree node.
* struct c {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* result;
bool isInside(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == NULL) {
return 0;
}
bool left, right;
left = isInside(root->left, p, q);
right = isInside(root->right, p, q);
if ((right && left) || ((root == p || root == q) && (left || right))) {
result = root;
return 0;
}
if (left || right || root == p || root == q)
return 1;
return 0;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
isInside(root, p, q);
return result;
}
};