题目:
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5
For example, the lowest common ancestor (LCA) of nodes 2
and 8
is 6
. Another example is LCA of nodes 2
and 4
is 2
, since a node can be a descendant of itself according to the LCA definition.
分析:记录p和q的路径,然后找到p和q路径前面共同的路径,最后一个节点就是LCA
代码:
/**
* 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==NULL||p==NULL||q==NULL)
{
return NULL;
}
int pval=p->val;
int qval=q->val;
int pdeep,qdeep;
pdeep=1;
qdeep=1;
vector<bool>pnumv;
vector<bool>qnumv;
TreeNode* root1=root;
TreeNode* root2=root;
TreeNode* root3=root;
int pnum=1;
int qnum=1;
pnumv.clear();
qnumv.clear();
pnumv.push_back(1);
qnumv.push_back(1);
while(1)
{
if(p==root3)
{
break;
}
else
{
if(pval<(root3->val))
{
root3=root3->left;
pnumv.push_back(0);
}
else
{
root3=root3->right;
pnumv.push_back(1);
}
}
}
while(1)
{
if(q==root1)
{
break;
}
else
{
if(qval<(root1->val))
{
root1=root1->left;
qnumv.push_back(0);
}
else
{
root1=root1->right;
qnumv.push_back(1);
}
}
}
for(int i=1; (i<(pnumv.size()))&&(i<qnumv.size()); i++)
{
if(pnumv[i]!=qnumv[i])
{
break;
}
if(pnumv[i]==qnumv[i])
{
if(pnumv[i]==0)
{
root2=root2->left;
}
else
{
root2=root2->right;
}
}
}
return root2;
}
};