convert binary tree to double linked list
Utilisateur anonyme
I'm going through that process right now. Hopefully in between the phone screens and onsite interview but I may well just be at the end of the road with Amazon. I'll find out I suppose. I didn't get anything close to this question though. But here's my shot. If you need to use the same nodes and keep them in order, you might consider right and left to be prev and next and make the binary search tree no longer a binary search tree and instead a doubly linked list. std::pair flatten_and_return_ends(node *root_node) { node *first, *last; if (root_node->left) { std::pair left_minmax = flatten_and_return_ends(root_node->left); first = left_minmax.first; left_minmax.second->right = root_node; root_node->left = left_minmax.second; } else first = root_node; if (root_node->right) { std::pair right_minmax = flatten_and_return_ends(root_node->right); root_node->right = right_minmax.first; right_minmax.first->left = root_node; last = right_minmax.second; } else last = root_node; return std::pair(first, last); } on the other hand, if they just want you to push the nodes in order into a list template void add_to_list(node *root_node, list &values) { if (root_node->left) add_to_list(root_node->left, values); values.push_back(root_node->value); if (root_node->right) add_to_list(root_node->right, values); } I didn't check for validity so there may be typos