1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public: int widthOfBinaryTree(TreeNode* root) { queue<pair<TreeNode*, pair<unsigned int, unsigned int>>> que; if(!root) return 0; unsigned int ans = 1, level = 0, curl, curi, li=0; que.push(pair(root, pair(0, 0))); while(!que.empty()) { root = que.front().first; curl = que.front().second.first; curi = que.front().second.second; que.pop(); if(curl!=level){ ++level, li=curi; } if(root->left) que.push(pair(root->left, pair(level+1, curi*2))); if(root->right) que.push(pair(root->right, pair(level+1, curi*2+1))); if(root) ans=max(curi-li+1, ans); } return ans; } };
|