1、前言
题目描述2、思路
利用满二叉树的性质来解题,如果 root 的索引为 i,则它的左孩子为 i * 2,右孩子为 i * 2 + 1。
3、代码
/**
* Definition for a binary tree node.
* 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) {
if(root == null){
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
int max = 0;
root.val = 1;
queue.offer(root);
while (!queue.isEmpty()){
int size = queue.size();
int start = queue.peek().val;
for(int i = 0; i < size; i++){
TreeNode node = queue.poll();
if(node.left != null){
node.left.val = node.val * 2;
queue.offer(node.left);
}
if(node.right != null){
node.right.val = node.val * 2 + 1;
queue.offer(node.right);
}
if(i == size - 1){
max = Math.max(max, node.val - start + 1);
}
}
}
return max;
}
}
网友评论