Skip to content

Commit 86b6841

Browse files
committed
feat: add solutions to lc problem: No.0662
No.0662.Maximum Width of Binary Tree
1 parent 8f04826 commit 86b6841

File tree

12 files changed

+568
-111
lines changed

12 files changed

+568
-111
lines changed

solution/0600-0699/0662.Maximum Width of Binary Tree/README.md

+194-38
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,21 @@
5757

5858
<!-- 这里可写通用的实现逻辑 -->
5959

60-
BFS 层序遍历。
60+
**方法一:BFS**
61+
62+
对节点进行编号,初始根节点编号为 $1$。
63+
64+
对于一个编号为 `i` 的节点,它的左节点编号为 `i<<1`,右节点编号为 `i<<1|1`
65+
66+
采用 BFS 进行层序遍历,求每层的宽度时,用该层的最大节点编号减去最小节点编号再加一即可。
67+
68+
时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。
69+
70+
**方法二:DFS**
71+
72+
定义 `dfs(root, depth, i)` 表示从深度为 `depth`,且编号为 `i` 的节点 `root` 开始往下搜索。记录每一层最先访问到的节点的编号。访问到当前层其它节点时,求当前节点编号与当前层最小编号的差再加一,更新当前层的最大宽度。
73+
74+
时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。
6175

6276
<!-- tabs:start -->
6377

@@ -73,18 +87,43 @@ BFS 层序遍历。
7387
# self.left = left
7488
# self.right = right
7589
class Solution:
76-
def widthOfBinaryTree(self, root: TreeNode) -> int:
77-
q = deque([(root, 1)])
90+
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
7891
ans = 0
92+
q = deque([(root, 1)])
7993
while q:
80-
n = len(q)
8194
ans = max(ans, q[-1][1] - q[0][1] + 1)
82-
for _ in range(n):
83-
node, j = q.popleft()
84-
if node.left:
85-
q.append((node.left, 2 * j))
86-
if node.right:
87-
q.append((node.right, 2 * j + 1))
95+
for _ in range(len(q)):
96+
root, i = q.popleft()
97+
if root.left:
98+
q.append((root.left, i << 1))
99+
if root.right:
100+
q.append((root.right, i << 1 | 1))
101+
return ans
102+
```
103+
104+
```python
105+
# Definition for a binary tree node.
106+
# class TreeNode:
107+
# def __init__(self, val=0, left=None, right=None):
108+
# self.val = val
109+
# self.left = left
110+
# self.right = right
111+
class Solution:
112+
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
113+
def dfs(root, depth, i):
114+
if root is None:
115+
return
116+
if len(t) == depth:
117+
t.append(i)
118+
else:
119+
nonlocal ans
120+
ans = max(ans, i - t[depth] + 1)
121+
dfs(root.left, depth + 1, i << 1)
122+
dfs(root.right, depth + 1, i << 1 | 1)
123+
124+
ans = 1
125+
t = []
126+
dfs(root, 0, 1)
88127
return ans
89128
```
90129

@@ -111,17 +150,19 @@ class Solution:
111150
class Solution {
112151
public int widthOfBinaryTree(TreeNode root) {
113152
Deque<Pair<TreeNode, Integer>> q = new ArrayDeque<>();
114-
q.offerLast(new Pair<>(root, 1));
153+
q.offer(new Pair<>(root, 1));
115154
int ans = 0;
116155
while (!q.isEmpty()) {
117156
ans = Math.max(ans, q.peekLast().getValue() - q.peekFirst().getValue() + 1);
118-
for (int i = 0, n = q.size(); i < n; ++i) {
119-
Pair<TreeNode, Integer> node = q.pollFirst();
120-
if (node.getKey().left != null) {
121-
q.offerLast(new Pair<>(node.getKey().left, node.getValue() * 2));
157+
for (int n = q.size(); n > 0; --n) {
158+
var p = q.pollFirst();
159+
root = p.getKey();
160+
int i = p.getValue();
161+
if (root.left != null) {
162+
q.offer(new Pair<>(root.left, i << 1));
122163
}
123-
if (node.getKey().right != null) {
124-
q.offerLast(new Pair<>(node.getKey().right, node.getValue() * 2 + 1));
164+
if (root.right != null) {
165+
q.offer(new Pair<>(root.right, i << 1 | 1));
125166
}
126167
}
127168
}
@@ -130,9 +171,49 @@ class Solution {
130171
}
131172
```
132173

174+
```java
175+
/**
176+
* Definition for a binary tree node.
177+
* public class TreeNode {
178+
* int val;
179+
* TreeNode left;
180+
* TreeNode right;
181+
* TreeNode() {}
182+
* TreeNode(int val) { this.val = val; }
183+
* TreeNode(int val, TreeNode left, TreeNode right) {
184+
* this.val = val;
185+
* this.left = left;
186+
* this.right = right;
187+
* }
188+
* }
189+
*/
190+
class Solution {
191+
private int ans = 1;
192+
private List<Integer> t = new ArrayList<>();
193+
194+
public int widthOfBinaryTree(TreeNode root) {
195+
dfs(root, 0, 1);
196+
return ans;
197+
}
198+
199+
private void dfs(TreeNode root, int depth, int i) {
200+
if (root == null) {
201+
return;
202+
}
203+
if (t.size() == depth) {
204+
t.add(i);
205+
} else {
206+
ans = Math.max(ans, i - t.get(depth) + 1);
207+
}
208+
dfs(root.left, depth + 1, i << 1);
209+
dfs(root.right, depth + 1, i << 1 | 1);
210+
}
211+
}
212+
```
213+
133214
### **C++**
134215

135-
`start * 2` 表示下一层的起点。计算下一层左右子树索引时,减去 `start * 2`,可以防止溢出。
216+
`i << 1` 表示下一层的起点。计算下一层左右子树索引时,减去 `i << 1`,可以防止溢出。
136217

137218
```cpp
138219
/**
@@ -150,23 +231,61 @@ class Solution {
150231
public:
151232
int widthOfBinaryTree(TreeNode* root) {
152233
queue<pair<TreeNode*, int>> q;
153-
q.emplace(root, 1);
234+
q.push({root, 1});
154235
int ans = 0;
155236
while (!q.empty()) {
156237
ans = max(ans, q.back().second - q.front().second + 1);
157-
int start = q.front().second;
158-
for (int i = 0, n = q.size(); i < n; ++i) {
159-
auto node = q.front();
238+
int i = q.front().second;
239+
for (int n = q.size(); n; --n) {
240+
auto p = q.front();
160241
q.pop();
161-
if (node.first->left != nullptr) q.emplace(node.first->left, node.second * 2 - start * 2);
162-
if (node.first->right != nullptr) q.emplace(node.first->right, node.second * 2 + 1 - start * 2);
242+
root = p.first;
243+
int j = p.second;
244+
if (root->left) q.push({root->left, (j << 1) - (i << 1)});
245+
if (root->right) q.push({root->right, (j << 1 | 1) - (i << 1)});
163246
}
164247
}
165248
return ans;
166249
}
167250
};
168251
```
169252
253+
```cpp
254+
/**
255+
* Definition for a binary tree node.
256+
* struct TreeNode {
257+
* int val;
258+
* TreeNode *left;
259+
* TreeNode *right;
260+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
261+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
262+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
263+
* };
264+
*/
265+
class Solution {
266+
public:
267+
vector<int> t;
268+
int ans = 1;
269+
using ull = unsigned long long;
270+
271+
int widthOfBinaryTree(TreeNode* root) {
272+
dfs(root, 0, 1);
273+
return ans;
274+
}
275+
276+
void dfs(TreeNode* root, int depth, ull i) {
277+
if (!root) return;
278+
if (t.size() == depth) {
279+
t.push_back(i);
280+
} else {
281+
ans = max(ans, (int) (i - t[depth] + 1));
282+
}
283+
dfs(root->left, depth + 1, i << 1);
284+
dfs(root->right, depth + 1, i << 1 | 1);
285+
}
286+
};
287+
```
288+
170289
### **Go**
171290

172291
```go
@@ -178,31 +297,68 @@ public:
178297
* Right *TreeNode
179298
* }
180299
*/
181-
type Node struct {
182-
node *TreeNode
183-
idx int
184-
}
185-
186300
func widthOfBinaryTree(root *TreeNode) int {
187-
q := []Node{{root, 1}}
301+
q := []pair{{root, 1}}
188302
ans := 0
189303
for len(q) > 0 {
190-
ans = max(ans, q[len(q)-1].idx-q[0].idx+1)
191-
n := len(q)
192-
for i := 0; i < n; i++ {
193-
node := q[0]
304+
ans = max(ans, q[len(q)-1].i-q[0].i+1)
305+
for n := len(q); n > 0; n-- {
306+
p := q[0]
194307
q = q[1:]
195-
if node.node.Left != nil {
196-
q = append(q, Node{node.node.Left, node.idx * 2})
308+
root = p.node
309+
if root.Left != nil {
310+
q = append(q, pair{root.Left, p.i << 1})
197311
}
198-
if node.node.Right != nil {
199-
q = append(q, Node{node.node.Right, node.idx*2 + 1})
312+
if root.Right != nil {
313+
q = append(q, pair{root.Right, p.i<<1 | 1})
200314
}
201315
}
202316
}
203317
return ans
204318
}
205319

320+
type pair struct {
321+
node *TreeNode
322+
i int
323+
}
324+
325+
func max(a, b int) int {
326+
if a > b {
327+
return a
328+
}
329+
return b
330+
}
331+
```
332+
333+
```go
334+
/**
335+
* Definition for a binary tree node.
336+
* type TreeNode struct {
337+
* Val int
338+
* Left *TreeNode
339+
* Right *TreeNode
340+
* }
341+
*/
342+
func widthOfBinaryTree(root *TreeNode) int {
343+
ans := 1
344+
t := []int{}
345+
var dfs func(root *TreeNode, depth, i int)
346+
dfs = func(root *TreeNode, depth, i int) {
347+
if root == nil {
348+
return
349+
}
350+
if len(t) == depth {
351+
t = append(t, i)
352+
} else {
353+
ans = max(ans, i-t[depth]+1)
354+
}
355+
dfs(root.Left, depth+1, i<<1)
356+
dfs(root.Right, depth+1, i<<1|1)
357+
}
358+
dfs(root, 0, 1)
359+
return ans
360+
}
361+
206362
func max(a, b int) int {
207363
if a > b {
208364
return a

0 commit comments

Comments
 (0)