Bloomberg Interview Question

Find closest ancestor in a tree

Interview Answer

Anonymous

Aug 17, 2017

//Find closest ancestor in a tree class Node { public: int value; Node *left; Node *right; }; void recursiveSearch(Node* root, vector &path, int v) { path.push_back(root->value); if(root->value == v) { return; } if(v > root->value) { recursiveSearch(root->right, path, v); } else { recursiveSearch(root->left, path, v); } return; } int findAncestor(Node* root, int v1, int v2) { vector pathV1; vector pathV2; int ancestor; recursiveSearch(root, pathV1, v1); recursiveSearch(root, pathV2, v2); bool found = false; for(int i = pathV1.size() - 1; i >= 0 && found == false; i++) { for(int j = pathV2.size() - 1; j >= 0 && found == false; j++) { if(pathV1[i] == pathV2[j]) { found = true; ancestor = pathV1[i]; } } } return ancestor; }