二叉树

//定义二叉树节点
struct TreeNode
{
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
//由链表创建树
TreeNode* createTree(int *list, int start)
{
	if (list[start] == 0)
	{
		return NULL;
	}

	TreeNode* root = new TreeNode(list[start]);

	int lnode = 2 * start + 1;
	int rnode = 2 * start + 2;
	if (lnode > sizeof(list) - 1) {
		root->left = NULL;
	}
	else {
		root->left = createTree(list, lnode);
	}

	if (rnode > sizeof(list) - 1) {
		root->right = NULL;
	}
	else {
		root->right = createTree(list, rnode);
	}

	return root;
}
void PreOrder(TreeNode * root)  //先序遍历
{
	if (root != NULL)
	{
		cout << root->val << " ";
		PreOrder(root->left);
		PreOrder(root->right);
	}
}
void InOrder(TreeNode *root)  //中序遍历
{
	if (root != NULL)
	{
		InOrder(root->left);
		cout << root->val << " ";
		InOrder(root->right);
	}
}
void PostOrder(TreeNode *root)  //后序遍历
{
	if (root != NULL)
	{
		PostOrder(root->left);
		PostOrder(root->right);
		cout << root->val << " ";
	}
}
void LevelOrder(TreeNode *root)  //层次遍历
{
	int front, rear;
	TreeNode *que[MaxSize];
	front = rear = 0;
	TreeNode *q;
	if (root != 0)
	{
		rear = (rear + 1) % MaxSize;
		que[rear] = root;
		while (front != rear)
		{
			front = (front + 1) % MaxSize;
			q = que[front];
			cout << q->val << " ";
			if (q->left != 0)
			{
				rear = (rear + 1) % MaxSize;
				que[rear] = q->left;
			}
			if (q->right != 0)
			{
				rear = (rear + 1) % MaxSize;
				que[rear] = q->right;
			}
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值