Meta Interview Question

Given a binary tree, print the average of each level.

Interview Answers

Anonymous

Dec 8, 2015

That's exactly what I did.

1

Anonymous

Dec 14, 2015

It can be done with only one Queue, doing a level traversal and each time we are in a new level we insert a dummy node(can be null)to separate the levels, while doing the traversal we just keep adding the nodes we are inserting and keep the count of how many nodes we have so when we find a null pointer we just divide the current sum by the current count.

Anonymous

Jul 13, 2016

vector TreeAverage(TreeNode* root) { vector result; if(root == NULL) return result; queue<div>q; q.push_back(root); while(!q.empty()) { int size = q.size(); int temp; int sum = 0; while(temp) { TreeNode* currNode = q.front(); q.pop(); sum = sum + q->val; if(q->left) { q.push(q->left); } if(q->right) { q.push(q->right); } temp--; } result.push_back(sum / size); } return result; }</div>

Anonymous

Jul 13, 2016

Update to previous submission : queue<div>q; int temp = size;</div>

Anonymous

Dec 8, 2015

use two queues, one for current level, one for level below, then it's just iterating over a queue