How do you find the next highest element in a binary search tree?
Anonymous
I posted following code two weeks back, but someone removed it :( Let me post it again: typedef struct node_type { int info; struct node_type *parent; struct node_type *left; struct node_type *right; } node_type_t; node_type_t *_find_next(node_type_t *nodep, int *count) { static node_type_t *srcnd = NULL; static int scan_down = 1; if (nodep == NULL) { printf("find_next(node='%d'): got error\n", (srcnd != NULL ? srcnd->info : -1)); return NULL; } if (*count == 0) { srcnd = nodep; *count += 1; } if (nodep->info info) { if (nodep->parent != NULL) return(_find_next(nodep->parent, count)); else { printf("Can't find next node of '%d'\n", srcnd->info); return NULL; } } else if (nodep->info > srcnd->info) { if (!scan_down) return nodep; if (nodep->left != NULL) _find_next(nodep->left, count); else return nodep; } else { // nodep->info == srcnd->info if (nodep->right != NULL) { scan_down = 1; _find_next(nodep->right, count); } else { scan_down = 0; _find_next(nodep->parent, count); } } } node_type_t *find_next(node_type_t *nodep) { int count = 0; return (_find_next(nodep, &count)); } Interviewer said to me that recursive approach is not right solution, but above code is much better performance than his answer ;). The problem is that I couldn't answer the question within the interview time. I email above code to interviewer, on next day I got response that Arista doesn't have any position for me. :(
Check out your Company Bowl for anonymous work chats.