BST:
/**
* 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) {
if (!root) return NULL;
int a = p->val < q->val ? p->val : q->val;
int b = p->val > q->val ? p->val : q->val;
if (a <= root->val && b >= root->val) {
return root;
}
if (a < root->val && b < root->val) {
return lowestCommonAncestor(root->left, p, q);
}
if (a > root->val && b > root->val) {
return lowestCommonAncestor(root->right, p, q);
}
}
};BT:
/**
* 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:
bool traverse(TreeNode* root, TreeNode *p, TreeNode *q, TreeNode *&res) {
if (!root) return false;
if (root == p && root == q) {
res = root;
return true;
}
bool f = false;
if (root == p || root == q) {
f = true;
}
bool fl = traverse(root->left, p, q, res);
bool fr = traverse(root->right, p, q, res);
if (!res && ((fl && fr) || (f && fl) || (f && fr))) {
res = root;
return true;
} else {
return (f || fl || fr);
}
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
TreeNode *res = NULL;
traverse(root, p, q, res);
return res;
}
};
441

被折叠的 条评论
为什么被折叠?



