Advertisement
varun1729

Untitled

May 4th, 2023
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. int maxwidth(struct TreeNode* root) {
  2. if (!root) {
  3. return 0;
  4. }
  5. int maxWidth = 0;
  6. struct TreeNode** queue = (struct TreeNode**) malloc(sizeof(struct TreeNode*) * 1000);
  7. int front = 0, rear = 0;
  8. queue[rear++] = root;
  9. while (front != rear) {
  10. int size = rear - front;
  11. int leftmost = 0, rightmost = 0;
  12. for (int i = 0; i < size; i++) {
  13. struct TreeNode* node = queue[front++];
  14. if (i == 0) {
  15. leftmost = node->val;
  16. }
  17. if (i == size - 1) {
  18. rightmost = node->val;
  19. }
  20. if (node->left) {
  21. node->left->val = node->val * 2;
  22. queue[rear++] = node->left;
  23. }
  24. if (node->right) {
  25. node->right->val = node->val * 2 + 1;
  26. queue[rear++] = node->right;
  27. }
  28. }
  29. int width = rightmost - leftmost + 1;
  30. maxWidth = maxWidth < width ? width : maxWidth;
  31. }
  32. free(queue);
  33. return maxWidth;
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement