Skip to content

Commit 36a9770

Browse files
committed
09/14
1 parent 885b9f0 commit 36a9770

2 files changed

Lines changed: 58 additions & 0 deletions

File tree

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ Feel free to add issues, comment and pull request.
7272
| Leetcode | [637. Average of Levels in Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree/description/) | [Java](./java/averageOfLevels.java) \| [Python](./Python/) | _O(n)_ | _O(1)_ | Easy | |
7373
| Leetcode | [663. Equal Tree Partition](https://leetcode.com/problems/equal-tree-partition/description/) | [Java](./java/CheckEqualTrees.java) \| [Python](./Python/) | | | Medium | |
7474
| Leetcode | [623. Add One Row to Tree](https://leetcode.com/problems/add-one-row-to-tree/description/) | [Java](./java/addOneRow.java) \| [Python](./Python/) | | | Medium | |
75+
| Leetcode | [662. Maximum Width of Binary Tree](https://leetcode.com/problems/maximum-width-of-binary-tree/description/) | [Java](./java/widthOfBinaryTree.java) \| [Python](./Python/) | O(n) | O(d) | Medium | |
7576

7677

7778
## Dynamic Programming

java/widthOfBinaryTree.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
11+
12+
/*
13+
use a travel traversal template, use another queue to keep the index of each level nodes. left node index = this node index * 2, right = this node index*2 + 1. the width should be the last node index - first node index + 1
14+
15+
*/
16+
class Solution {
17+
public int widthOfBinaryTree(TreeNode root) {
18+
if(root == null) return 0;
19+
Queue<TreeNode> queue = new ArrayDeque<>();
20+
Queue<Integer> count = new ArrayDeque<>();
21+
int max = 1;
22+
23+
queue.offer(root);
24+
count.offer(1);
25+
26+
while(!queue.isEmpty())
27+
{
28+
int size = queue.size();
29+
int left = 0;
30+
int right = 0;
31+
32+
for(int i=0; i<size; i++)
33+
{
34+
TreeNode node = queue.poll();
35+
int index = count.poll();
36+
if(i==0) left = index;
37+
if(i==size-1) right = index;
38+
39+
if(node.left != null)
40+
{
41+
queue.offer(node.left);
42+
count.offer(index*2);
43+
}
44+
45+
if(node.right != null)
46+
{
47+
queue.offer(node.right);
48+
count.offer(index*2+1);
49+
}
50+
}
51+
52+
max = Math.max(max, right - left+1);
53+
}
54+
55+
return max;
56+
}
57+
}

0 commit comments

Comments
 (0)