Pergunta de entrevista da empresa Arista Networks

Write code to find in-order successor in a binary tree.

Respostas da entrevista

Sigiloso

21 de jun. de 2012

It's very easy to do recursively, but I was also asked to do this iteratively.

1

Sigiloso

23 de jul. de 2012

typedef struct _node { struct _node *left; struct _node *right; int data; }NODE; int inorder_successor(NODE *root, int key) { NODE *tmp, *successor; tmp=successor=root; while(tmp) { if(tmp->data==key) break; else if(keydata) { successor=tmp; tmp=tmp->left; } /*Save successor before taking left because you might just be the successor!*/ else tmp=tmp->right; } if(!tmp || tmp==successor) return -1; /*key itself not found OR only root-node present*/ if(tmp->right) return (min_node(tmp->right)); if(tmp->data == max_node(root)) return -1; /*we reached the rightmost node i.e. max element; hence return -1*/ else return successor->data; }