剑指offer-刷题笔记-简单题-JZ32 从上往下打印二叉树
版本1用了递归调用,实际上实现了先序遍历,根左右访问节点,无法做到同层,如下图,先序遍历为ABDECF,如果是本题为ABCDEF,版本2通过队列实现了二叉树的层次遍历
版本1-自己写的递归,部分正确
class Solution {
public:
vector<int> result;
bool flag = true;
void pushNode(TreeNode* root)
{
if(root != nullptr)
{
result.push_back(root->val);
if(root->left != nullptr || root->right != nullptr)
{
pushNode(root->left);
pushNode(root->right);
}
}
}
vector<int> PrintFromTopToBottom(TreeNode* root) {
pushNode(root);
return result;
}
};
版本2-建立辅助队列- 层次遍历
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
vector<int> ret;
if (!root) {
return ret;
}
queue<TreeNode*> q;
q.push(root);
while(!q.empty()) {
int size = q.size();
for (int i=0; i<size; i++) {
TreeNode *p = q.front();
q.pop();
ret.push_back(p->val);
if (p->left) {
q.push(p->left);
}
if (p->right) {
q.push(p->right);
}
}
}
return ret;
}
};