-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy path662-二叉树最大宽度.cpp
More file actions
51 lines (51 loc) · 1.37 KB
/
662-二叉树最大宽度.cpp
File metadata and controls
51 lines (51 loc) · 1.37 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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
if(root == NULL)
return 0;
deque<TreeNode*> deq;//双向队列
int maxLen = 0;
deq.push_back(root);
while(!deq.empty())
{
int len = deq.size();//上一层的宽度
maxLen = max(maxLen, len);
while(len--)
{
TreeNode* node = deq.front();
deq.pop_front();
if(node)
{
deq.push_back(node->left);
deq.push_back(node->right);
}
else
{
//因为NULL也要计算长度,加入队列
deq.push_back(NULL);
deq.push_back(NULL);
}
}
//对当前层处理,去掉左右端的空节点
while(!deq.empty())
{
if(deq.front() == NULL)
deq.pop_front();
else if(deq.back() == NULL)
deq.pop_back();
else
break;
}
}
return maxLen;
}
};