您的位置:首页 > 编程语言 > C语言/C++

leetcode 日经贴,Cpp code -Lowest Common Ancestor of a Binary Search Tree

2015-07-11 21:06 567 查看
Lowest Common Ancestor of a Binary
Search Tree

/**
* 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) {
matchcnt = 0;
if (!root || !p || !q) {
return NULL;
}
return lca(root, p, q);
}
private:
TreeNode* lca(TreeNode *r, TreeNode *p, TreeNode *q) {
if (!r) {
return NULL;
}
int a = matchcnt;
TreeNode *ret = lca(r->left, p, q);
if (ret) {
return ret;
}
ret = lca(r->right, p, q);
if (ret) {
return ret;
}
if (r == p || r == q) {
++matchcnt;
}
if (a == 0 && matchcnt == 2) {
return r;
}
return NULL;
}
int matchcnt;
};


/**
* 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 || !p || !q) {
return NULL;
}
if (p->val > q->val) {
swap(p, q);
}
return lca(root, p, q);
}
private:
TreeNode* lca(TreeNode *r, TreeNode *p, TreeNode *q) {
if (!r) {
return NULL;
}
if (r->val >= p->val && r->val <= q->val) {
return r;
}
if (r->val < p->val) {
return lca(r->right, p, q);
} else {
return lca(r->left, p, q);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: