Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. class Solution {
  2. public:
  3. int widthOfBinaryTree(TreeNode* root) {
  4. if (!root)
  5. return 0;
  6.  
  7. queue<pair<TreeNode*, uint>> q;
  8. q.push(make_pair(root, 0));
  9.  
  10. uint width = 0;
  11. while (!q.empty()) {
  12. int size_q = q.size();
  13.  
  14. uint lo = q.front().second;
  15. uint hi = q.front().second;
  16. while (size_q--) {
  17. TreeNode* cur = q.front().first;
  18. uint id = q.front().second;
  19. q.pop();
  20.  
  21. hi = id;
  22. if (cur->left) q.push(make_pair(cur->left, id*2 + 1));
  23. if (cur->right) q.push(make_pair(cur->right, id*2 + 2));
  24. }
  25.  
  26. width = max(width, hi - lo + 1);
  27. }
  28.  
  29. return width;
  30. }
  31. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement