BinaryTreeNode* getCommonAncestor(BinaryTreeNode* root, BinaryTreeNode* firstNode, BinaryTreeNode* secondNode) { if (root == NULL || firstNode == NULL || secondNode == NULL) { return NULL; } int firstNodeDepth = getNodeDepth(root, firstNode); int secondNodeDepth = getNodeDepth(root, firstNode); int diff = firstNodeDepth - secondNodeDepth; bool firstPathLonger = true; if (firstNodeDepth < secondNodeDepth) { diff = secondNodeDepth - firstNodeDepth; firstPathLonger = false; } if (firstPathLonger) { alignByTrail(firstNode, diff); } else { alignByTrail(secondNode, diff); } while (firstNode != NULL && firstNode != secondNode) { firstNode = firstNode->parent; secondNode = secondNode->parent; } return firstNode; }
//------------------------------------------------------------------------------ // Compute node depth (i.e, height above root). Based on COMPONENT 2.0 code, // assumes count is set to 0 prior to calling code void Tree::getNodeDepth(NodePtr p) { if (p) { p->SetDepth (count); count++; getNodeDepth (p->GetChild()); count--; getNodeDepth (p->GetSibling()); } }
//------------------------------------------------------------------------------ // Compute node depth (i.e, height above root). void Tree::GetNodeDepths () { count = 0; getNodeDepth (Root); }