题目
法1:BFS,最佳方法
class Solution {
public int widthOfBinaryTree(TreeNode root) {
int ans = 0;
Deque<TreeNode> deque = new LinkedList<>();
deque.offer(new TreeNode(1, root.left, root.right));
while(!deque.isEmpty()) {
int count = deque.size(), startIndex = -1, endIndex = -1;
for (int i = 0; i < count; i++) {
TreeNode node = deque.pop();
endIndex = node.val;
if (startIndex == -1) {
startIndex = node.val;
}
if (node.left != null) {
deque.offerLast(new TreeNode(node.val * 2, node.left.left, node.left.right));
}
if (node.right != null) {
deque.addLast(new TreeNode(node.val * 2 + 1, node.right.left, node.right.right));
}
}
ans = Math.max(ans, endIndex - startIndex + 1);
}
return ans;
}
}