TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { // swap p and q if p has a larger val. if (p->val > q->val) { TreeNode* swap = p; p = q; q = swap; } bool p_isLeft = isUnder(root->left, p); bool q_isRight = isUnder(root->right, q); bool p_isRight = isUnder(root->right, p); bool q_isLeft = isUnder(root->left, q); // Is p left or myself? // Is q right or myself? // If both yes, then I am the LCA; if ( (p_isLeft || (p == root)) && (q_isRight || (q == root)) ) return root; // Are both p and q to the left? Then the LCA is somewhere under my left node. if ( p_isLeft && q_isLeft ) return lowestCommonAncestor(root->left, p, q); // Are both p and q to the right? Then the LCA is somewhere under my right node. if ( p_isRight && q_isRight ) return lowestCommonAncestor(root->right, p, q); }
bool isUnder(TreeNode* root, TreeNode* x) { if (root == NULL) return false; if ( (root == x) || isUnder(root->left, x) || isUnder(root->right, x) ) return true; else return false; }
/** * Update the massObject%'s position so that it lands on any baseable spriteObject%s that it may otherwise * pass through in the tick. */ void massObject::checkPenetration() { for (vector<spriteObject*>::iterator it = sm->gameSprites.begin(); it != sm->gameSprites.end(); ++it) { if (*it == this || !(*it)->isBaseable()) continue; if (inVertPlaneOf(*it) && isOver(*it)) { y += vy; if (isUnder(*it) || inHorizPlaneOf(*it)) { y -= vy; //round y off first s16 rounds = y % 256; y += rounds; //adjust vertical velocity accordingly. vy = (*it)->getTop() - getBottom(); vy = vy<<8; } else { y -= vy; } } } }