fork download
  1. #include <stdio.h>
  2.  
  3. struct Node {
  4. Node(Node *left, Node *right, int val) : left(left), right(right), next(NULL), val(val) {}
  5. Node *left, *right, *next;
  6. int val;
  7. };
  8.  
  9. void LinkTreeWithoutNils (Node* node)
  10. {
  11. if (!node)
  12. return;
  13. Node *left = node->left, *right = node->right;
  14. LinkTreeWithoutNils(left);
  15. LinkTreeWithoutNils(right);
  16. while (left)
  17. {
  18. left->next = right;
  19. left = left->right ? left->right : left->left;
  20. if (right) right = right->left;
  21. }
  22. }
  23.  
  24. void LinkTree (Node* node)
  25. {
  26. LinkTreeWithoutNils(node);
  27. Node* right = node;
  28. while (right)
  29. {
  30. right->next = NULL;
  31. right = right->right;
  32. }
  33. }
  34.  
  35. void ShowNode(Node *node)
  36. {
  37. printf("val=%d left=%d right=%d next=%d\n", node->val,
  38. node->left ? node->left->val : -1,
  39. node->right ? node->right->val : -1,
  40. node->next ? node->next->val : -1);
  41. }
  42.  
  43. int main(void) {
  44. Node leaf1(NULL, NULL, 1);
  45. Node leaf2(NULL, NULL, 3);
  46. Node mid1(&leaf1, NULL, 4);
  47. Node mid2(NULL, &leaf2, 5);
  48. Node root(&mid1, &mid2, 6);
  49. LinkTree(&root);
  50.  
  51. ShowNode(&leaf1);
  52. ShowNode(&leaf2);
  53. ShowNode(&mid1);
  54. ShowNode(&mid2);
  55. ShowNode(&root);
  56. return 0;
  57. }
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
val=1 left=-1 right=-1 next=-1
val=3 left=-1 right=-1 next=-1
val=4 left=1 right=-1 next=5
val=5 left=-1 right=3 next=-1
val=6 left=4 right=5 next=-1