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.
Subscribe to see which companies asked this question
这题做的不是很好。
代码
代码
/**
* 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 findNode(TreeNode* root, TreeNode* p,vector<TreeNode*>& result)
{
if(root == NULL)
{
return false;
}
if(root == p)
{
result.push_back(root);
return true;
}
bool temp=false;
if(!temp)
{ result.push_back(root);
temp=findNode(root->left,p,result)||findNode(root->right,p,result);
if(!temp)
result.pop_back();
}
return temp;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
vector<TreeNode*> p1;
vector<TreeNode*> p2;
findNode(root,p,p1);
findNode(root,q,p2);
int len1=p1.size();
int len2=p2.size();
int t =min(len1,len2);
while(--t>=0)
{
if(p1[t]==p2[t])
return p1[t];
}
return p1[0];
}
};