广度优先、就是每一层遍历完,再遍历下一层;
深度优先是一条路走到底;再回头走没走完的接着走;都是按照中序遍历走的
一下是广度优先
一个queue存每层的root,在当前层的节点的left和right子节点push进去,当前层的节点pop完后,记录queue的size就知道有下一层有多少个节点;
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
auto avg = vector<double>();
auto q = queue<TreeNode*>();
q.push(root);
while(!q.empty())
{
double sum = 0;
int size = q.size();
for(int i = 0; i < size; i++)
{
TreeNode* node = q.front();
sum += node->val;
q.pop();
if(node->left)
q.push(node->left);
if(node->right)
q.push(node->right);
}
avg.push_back(sum / size);
}
return avg;
}
};