Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- #include <climits>
- using namespace std;
- // Definition for a binary tree node.
- struct TreeNode {
- int val;
- TreeNode *left;
- TreeNode *right;
- TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
- };
- // Construct a binary tree from a level order traversal array.
- TreeNode* constructTree(vector<int>& nodes) {
- if (nodes.empty()) {
- return nullptr;
- }
- TreeNode* root = new TreeNode(nodes[0]);
- queue<TreeNode*> q;
- q.push(root);
- size_t i = 1;
- while (!q.empty() && i < nodes.size()) {
- TreeNode* parent = q.front();
- q.pop();
- int leftVal = nodes[i++];
- int rightVal = i < nodes.size() ? nodes[i++] : 0;
- if (leftVal != -1) {
- parent->left = new TreeNode(leftVal);
- q.push(parent->left);
- }
- if (rightVal != -1) {
- parent->right = new TreeNode(rightVal);
- q.push(parent->right);
- }
- }
- return root;
- }
- // Compute the maximum width of a binary tree.
- int maxwidth(TreeNode* root) {
- if (root == nullptr) {
- return 0;
- }
- int maxWidth = INT_MIN;
- queue<pair<TreeNode*, int>> q;
- q.push({root, 0});
- while (!q.empty()) {
- int size = q.size();
- int left = INT_MAX, right = INT_MIN;
- for (int i = 0; i < size; i++) {
- auto node = q.front();
- q.pop();
- if (node.first->left) {
- q.push({node.first->left, 2 * node.second});
- left = min(left, 2 * node.second);
- }
- if (node.first->right) {
- q.push({node.first->right, 2 * node.second + 1});
- right = max(right, 2 * node.second + 1);
- }
- }
- maxWidth = max(maxWidth, right - left + 1);
- }
- return maxWidth;
- }
- int main() {
- int n;
- cin >> n;
- vector<int> nodes(n);
- for (int i = 0; i < n; i++) {
- cin >> nodes[i];
- if (nodes[i] == -1) {
- nodes[i] = 0;
- }
- }
- TreeNode* root = constructTree(nodes);
- int maxWidth = maxwidth(root);
- cout << maxWidth << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement