-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximum_width_of_binary_tree.cpp
More file actions
67 lines (63 loc) · 1.82 KB
/
maximum_width_of_binary_tree.cpp
File metadata and controls
67 lines (63 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
* =====================================================================================
*
* Filename: maximum_width_of_binary_tree.cpp
*
* Description: 662. Maximum Width of Binary Tree
* https://leetcode.com/problems/maximum-width-of-binary-tree/
*
* Version: 1.0
* Created: 03/01/2022 09:08:16
* Revision: none
* Compiler: gcc
*
* Author: xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <queue>
#include <utility>
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
if (root == nullptr) {
return 0;
}
uint64_t width = 0;
std::queue<std::pair<TreeNode*, uint64_t>> nodes;
nodes.push(std::make_pair(root, 0));
while (not nodes.empty()) {
width = std::max(width, nodes.back().second - nodes.front().second + 1);
int size = nodes.size();
while (size-- > 0) {
auto cur = nodes.front();
if (cur.first->left != nullptr) {
nodes.push(std::make_pair(cur.first->left, cur.second * 2 + 1));
}
if (cur.first->right != nullptr) {
nodes.push(std::make_pair(cur.first->right, cur.second * 2 + 2));
}
nodes.pop();
}
}
return static_cast<int>(width);
}
};
int main(int argc, char* argv[]) {
TreeNode* root = nullptr;
const int width = Solution().widthOfBinaryTree(root);
assert(width == 0);
return 0;
}