[leetcode] 235. Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
编译错误。。。不愿debug,之后继续
/**
* 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:
stack<TreeNode*> pst, qst;
bool Exist(TreeNode* root, TreeNode* t,stack<TreeNode*> st)
{
if(root)
{
if(t->val==root->val || ((root->left)&&Exist(root->left,t,st)) || ((root->right)&&Exist(root->right,t,st))
{
st.push(root);
return true;
}
}
return false;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
{
Exist(root,p,pst);
Exist(root,q,qst);
ListNode *lroot=root;
while(!pst.empty() && !qst.empty() && pst.top()==qst.top())
{
lroot=pst.top();
pst.push();
qst.push();
}
return lroot;
}
};

浙公网安备 33010602011771号