[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;
    }
};

  

posted @ 2016-03-22 11:44  白天黑夜每日c  阅读(111)  评论(0)    收藏  举报