下面利用c++实现的二叉树的层次遍历,这也是剑指offer中面试32题 ==> 从上到下打印二叉树,同一层中从左至右打印。
我分别使用队列queue和数组array来实现了这个遍历过程,总的来说两种方法的思路比较类似。
思路:都是先将节点放入容器中,然后再依次放入该节点的左右孩子节点,然后打印该节点,之后移动下标或弹出该节点。
具体的思路可以从代码中感受,只有自己去梳理并写一遍才是最深刻的哈哈<( ̄︶ ̄)↗[GO!]
#include<iostream>
#include<queue>
using namespace std;
typedef int element;
class Tree
{
public:
element val;
Tree *left;
Tree *right;
Tree(element x): val(x), left(nullptr), right(nullptr) {}
};
//方法1 队列实现
void hierarchy_queue(Tree *root) {
if (root==nullptr) return;
queue<Tree*> q;
q.push(root);
while (q.empty()==false) {
cout<<q.front()->val<<" ";
if (q.front()->left!=nullptr) {
q.push(q.front()->left);
}
if (q.front()->right!=nullptr) {
q.push(q.front()->right);
}
q.pop();
}
}
// 方法2 数组实现
void hierarchy_array(Tree *root) {
if (root==nullptr) return;
Tree* q[100];
int in, out = 0;
q[in++] = root;
while (in>out) {
if (q[out]!=nullptr) {
cout<<q[out]->val<<" ";
q[in++] = q[out]->left;
q[in++] = q[out]->right;
}
out++;
}
}
int main() {
Tree* root = new Tree(4);
root->left = new Tree(2);
root->left->left = new Tree(4);
root->left->right = new Tree(5);
cout<<"利用队列实现层次遍历:";
hierarchy_queue(root);
cout<<"\n利用数组实现层次遍历:" ;
hierarchy_array(root);
return 0;
}
最后的结果是: