Please avoid stating which problem these are solutions for.
During a recent discussion the following code was suggested
int desc(const Node* node, int d) { int l = d, r = d; if (node->l) l = desc(node->l, d + 1); if (node->r) r = desc(node->r, d + 1); // edit: thanks, Nico return max(l, r); } int d2(const Node* root) { return root ? desc(root, 1) : 0; }
One of the folks in the discussion shook his head and said: “If this was an interviewer, they would want you to do it in one function, though”. Then he presented this:
int d1(const Node* root) { if (root == nullptr) return 0; return max(d1(root->l) + 1, d1(root->r) + 1); }
Then he made the assertion “this is what an interviewer would be looking for”.
Recent Comments