标签:
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