码迷,mamicode.com
首页 > 其他好文 > 详细

Misc. - Lowest common ancestor - post-order traversal solution

时间:2015-01-27 07:03:07      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

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

Misc. - Lowest common ancestor - post-order traversal solution

标签:

原文地址:http://www.cnblogs.com/tonix/p/4251823.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!