输出结果:【3】,【20,9】,【15,7】,【nullptr,nullptr】
思路:
数组 temp 记录每一层的元素
数组res 记录最终结果
用深度 count 记录层数,如果为偶数,temp将头插,否则直接加入
代码:
void newOrder(treeNode* root,int count)
{
queueq;
if (root == nullptr)return;
q.push(root);
while (!q.empty())
{
vector temp;
int size = q.size();
for (int i = 0; i < size; i++)
{
treeNode* newNode = q.front();
q.pop();
if (count % 2 == 0)
{
temp.insert(temp.begin(), newNode->val);
}
else {
temp.push_back(newNode->val); //如果层数是奇数就直接放进去
}
if (newNode->left)q.push(newNode->left);
if (newNode->right)q.push(newNode->right);
}
count++;
res.push_back(temp);
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)