Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2019
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * struct TreeNode *left;
  6. * struct TreeNode *right;
  7. * };
  8. */
  9. /**
  10. * Return an array of arrays of size *returnSize.
  11. * The sizes of the arrays are returned as *columnSizes array.
  12. * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
  13. */
  14. #define MAX(a,b) ((a) > (b) ? a : b)
  15.  
  16. int getHeight(struct TreeNode* root);
  17. void fillret(struct TreeNode* root, int h, int l, int r, char ***ret);
  18.  
  19. char*** printTree(struct TreeNode* root, int** columnSizes, int* returnSize) {
  20.  
  21. int height = getHeight(root);
  22. int w = (1<<height) - 1; // 2^h -1
  23. *returnSize = w;
  24. printf("th height is %d, the w is %d", height, w);
  25. char*** ret=(char***)malloc(sizeof(char**)*height);
  26. *returnSize=height;
  27.  
  28. columnSizes[0]=(int*)malloc(sizeof(int)*height);
  29. for(int i=0;i<height;i++){
  30. columnSizes[0][i]=w;
  31. ret[i]=(char**)malloc(sizeof(char*)*w);
  32. for(int j=0;j<w;j++){
  33. ret[i][j]="";
  34. }
  35. }
  36.  
  37. fillret(root, 0, 0, w-1, ret);
  38. return ret;
  39. }
  40.  
  41.  
  42. int getHeight(struct TreeNode* root)
  43. {
  44. if(root == NULL )
  45. return 0;
  46.  
  47. return MAX(getHeight(root->left), getHeight(root->right)) + 1;
  48. }
  49.  
  50. void fillret(struct TreeNode* root, int h, int l, int r, char ***ret)
  51. {
  52. if(!root) return;
  53.  
  54. int midlle = (l + r) / 2;
  55. fillret(root->left, h+1, l, midlle - 1, ret);
  56. ret[h][midlle] = (char *)malloc(sizeof(char) * 4);
  57. sprintf(ret[h][midlle], "%d", root->val);
  58. fillret(root->right, h+1, midlle + 1, r, ret);
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement