-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTreeNode.java
55 lines (46 loc) · 1.14 KB
/
TreeNode.java
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
package ch1;
import java.util.Deque;
import java.util.LinkedList;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
public int widthOfBinaryTree(TreeNode root) {
int maxwidth=0;
if(root==null) return 0;
Deque<TreeNode>qu=new LinkedList<>();
qu.offer(root);
root.val=1;
while (!qu.isEmpty()){
int len=qu.size();
int left=qu.peekFirst().val;
int right=qu.peekLast().val;
maxwidth=Math.max(maxwidth,right-left+1);
for(int i =0;i <len;i++){
TreeNode node=qu.poll();
int position = node.val;
if(node.left!=null){
node.left.val = position*2;
qu.offer(node.left);
}
if(node.right!=null){
node.right.val = position*2+1;
qu.offer(node.right);
}
}
}
return maxwidth;
}
}