problem
solution
需要用一個整數紀錄最左邊與最右邊的節點的
- overflow
因為同一層最左邊的節點會基於跟節點的值去往上疊加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
27class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
// The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes are also counted into the length calculation.
// 最左邊與最右邊非空的節點
// bfs 變形
// 需要用一個整數紀錄最左邊與最右邊的節點的
queue<pair<TreeNode *,int> > q;
q.push(make_pair(root, 1));
int width = 0;
while(!q.empty()){
int size = q.size();
int l = q.front().second, r;
for(int i=0;i<size;++i){
pair<TreeNode*, int> p = q.front();
q.pop();
if(i==size-1) r = p.second;
if(p.first->left) q.push(make_pair(p.first->left, p.second*2));
if(p.first->right) q.push(make_pair(p.first->right, p.second*2+1));
}
width = max(width, r-l+1);
}
return width;
}
};
option 1
if(i==0) l = p.second;
, (p.second-l)
確保不會overflow
確保同一層最左邊的空節點,應該為0
to make the id starting from zero
1 | /** |
analysis
- time complexity
O(n)
- space complexity
O(n)