1.1二叉树打印

本文详细介绍了二叉树的前序、中序和后序遍历方法,包括递归和非递归实现,帮助读者理解二叉树的数据结构及其操作。
摘要由CSDN通过智能技术生成
#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值