Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Details not refined yet..

struct Ret
{
    Ret(TreeNode *p, Mask rm) : pVal(p), m(rm){}
    TreeNode *pVal;
    Mask m;
};

class Solution 
{
public:
    Ret lca(TreeNode *pRoot, int val0, int val1)
    {        
        if (!pRoot) return Ret(nullptr, NONE);

        //    1.    Leaf node
        if (!pRoot->left && !pRoot->right)
        {
            if (pRoot->val == val0) return Ret(pRoot, LEFT);
            if (pRoot->val == val1) return Ret(pRoot, RIGHT);
            return Ret(nullptr, NONE);
        }

        //    2. Inner node
        Ret rL(nullptr, NONE);
        if (pRoot->left)
        { 
            rL = lca(pRoot->left, val0, val1);            
            if (rL.m == BOTH) return rL;
        }
        
        Ret rR(nullptr, NONE);
        if (pRoot->right)
        {
            rR = lca(pRoot->right, val0, val1);
            if (rR.m == BOTH) return rR;
        }
        //    nodes in two sub-trees
        if (rL.pVal && rR.pVal) return Ret(pRoot, BOTH);

        //    3.    Root node
        Ret rM(nullptr, NONE);
        if (pRoot->val == val0 || pRoot->val == val1)
        {
            rM.pVal = pRoot;
            rM.m = LEFT;
        }        
        
        //    one of is root
        if (rM.pVal)
        {
            if (rL.pVal || rR.pVal)        return Ret(pRoot, BOTH);
            return Ret(pRoot, LEFT);
        }

        //    only one is found in subtree
        if (rL.pVal) return Ret(pRoot->left, LEFT);
        if (rR.pVal) return Ret(pRoot->right, RIGHT);

        //    not found
        return Ret(nullptr, NONE);
    }
};
posted on 2015-01-27 06:39  Tonix  阅读(188)  评论(0编辑  收藏  举报