Tree depth and width
Avg depth of tree
class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val){
this.val = val;
}
}
double avgDepth(TreeNode root){
if(root == null) return 0.0;
Queue<TreeNode> q = new LinkedList<>();
int sum = 0;
int count = 0;
int depth = 0;
q.add(root);
while(!q.isEmpty()){
depth++;
int size = q.size();
for(int i=0; i<size; i++){
TreeNode cur = q.poll();
if(cur.left==null && cur.right==null){
count++;
sum += depth;
}
if(cur.left != null){
q.add(cur.left);
}
if(cur.right != null){
q.add(cur.right);
}
}
}
return (double)sum/count;
}662. Maximum Width of Binary Tree
Last updated