#include <cstdlib>
#include <vector>
#include <typeinfo>
using namespace std;
struct Node {
int val;
struct Node* left;
struct Node* right;
Node(int x): val(x), left(NULL), right(NULL) {}
};
int main2() {
Node* q[550];
int head, tail;
int flag[550];
head = 0;
tail = 1 ;
q[tail] = root;
flag[q[tail]->val] = 0;
while(head != tail) {
head++;
Node *now = q[head];
if(now->left) q[++tail] = now->left, flag[now->left->val] = flag[now->val] + 1;
if(now->right) q[++tail] = now->right, flag[now->right->val] = flag[now->val] + 1;
}
vector<vector<int> > res; //二维矩阵
for(int i=1; i<=tail; i++) {
vector<int> tmp; //每层的集合
tmp.push_back(q[i]->val);
while(i+1 <= tail && flag[q[i+1]->val] == flag[q[i]->val]) {
tmp.push_back(q[i+1]->val);
i++;
}
res.push_back(tmp);
}
return res;
}
1.1二叉树打印
最新推荐文章于 2022-05-02 14:43:14 发布
本文详细介绍了二叉树的前序、中序和后序遍历方法,包括递归和非递归实现,帮助读者理解二叉树的数据结构及其操作。
摘要由CSDN通过智能技术生成