Advertisement
varun1729

Untitled

May 3rd, 2023
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <climits>
  5.  
  6. using namespace std;
  7.  
  8. // Definition for a binary tree node.
  9. struct TreeNode {
  10. int val;
  11. TreeNode *left;
  12. TreeNode *right;
  13. TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  14. };
  15.  
  16. // Construct a binary tree from a level order traversal array.
  17. TreeNode* constructTree(vector<int>& nodes) {
  18. if (nodes.empty()) {
  19. return nullptr;
  20. }
  21.  
  22. TreeNode* root = new TreeNode(nodes[0]);
  23. queue<TreeNode*> q;
  24. q.push(root);
  25. size_t i = 1;
  26.  
  27. while (!q.empty() && i < nodes.size()) {
  28. TreeNode* parent = q.front();
  29. q.pop();
  30. int leftVal = nodes[i++];
  31. int rightVal = i < nodes.size() ? nodes[i++] : 0;
  32.  
  33. if (leftVal != -1) {
  34. parent->left = new TreeNode(leftVal);
  35. q.push(parent->left);
  36. }
  37.  
  38. if (rightVal != -1) {
  39. parent->right = new TreeNode(rightVal);
  40. q.push(parent->right);
  41. }
  42. }
  43.  
  44. return root;
  45. }
  46.  
  47. // Compute the maximum width of a binary tree.
  48. int maxwidth(TreeNode* root) {
  49. if (root == nullptr) {
  50. return 0;
  51. }
  52.  
  53. int maxWidth = INT_MIN;
  54. queue<pair<TreeNode*, int>> q;
  55. q.push({root, 0});
  56.  
  57. while (!q.empty()) {
  58. int size = q.size();
  59. int left = INT_MAX, right = INT_MIN;
  60.  
  61. for (int i = 0; i < size; i++) {
  62. auto node = q.front();
  63. q.pop();
  64. if (node.first->left) {
  65. q.push({node.first->left, 2 * node.second});
  66. left = min(left, 2 * node.second);
  67. }
  68. if (node.first->right) {
  69. q.push({node.first->right, 2 * node.second + 1});
  70. right = max(right, 2 * node.second + 1);
  71. }
  72. }
  73.  
  74. maxWidth = max(maxWidth, right - left + 1);
  75. }
  76.  
  77. return maxWidth;
  78. }
  79.  
  80. int main() {
  81. int n;
  82. cin >> n;
  83. vector<int> nodes(n);
  84. for (int i = 0; i < n; i++) {
  85. cin >> nodes[i];
  86. if (nodes[i] == -1) {
  87. nodes[i] = 0;
  88. }
  89. }
  90.  
  91. TreeNode* root = constructTree(nodes);
  92. int maxWidth = maxwidth(root);
  93. cout << maxWidth << endl;
  94.  
  95. return 0;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement