二叉树

二叉树的链表存储结构

//二叉树的链表存储结构
struct node {
	int data;//数据域
	node* lchild;//指向左子树根节点的指针
	node* rchild;//指向右子树根节点的指针
};

新建结点

//新建结点
node* newNode(int v)
{
	node* n = new node;
	n->data = v;
	n->lchild = n->rchild = NULL;
	return n;
}

二叉树结点的查找、修改

//二叉树结点的查找、修改
void search(node* root, int x, int newdata)
{
	if (root == NULL)
	{
		return;
	}
	if (root->data == x)
	{
		//找到了
		root->data = newdata;
	}
	search(root->lchild, x, newdata);
	search(root->rchild, x, newdata);
}

二叉树结点的插入

//二叉树结点的插入
void insert(node*& root, int x)
{
	if (root == NULL)
	{
		root = newNode(x);
		return;
	}
	if (由于二叉树性质,x插在左子树)
	{
		insert(root->lchild, x);
	}
	else
	{
		insert(root->rchild, x);
	}
}

二叉树的创建

//二叉树的创建
node* Create(int data[], int n)
{
	node* root = NULL;
	for (int i = 0; i < n; i++)
	{
		insert(root, data[i]);
	}
	return root;
}

二叉树的先序遍历

//二叉树的先序遍历
void preorder(node* root)
{
	if (root == NULL)
	{
		return;
	}
	printf("%d", root->data);
	preorder(root->lchild);
	preorder(root->rchild);
}

二叉树的中序遍历

//二叉树的中序遍历
void inorder(node* root)
{
	if (root == NULL)
	{
		return;
	}
	inorder(root->lchild);
	printf("%d", root->data);
	inorder(root->rchild);
}

二叉树的后序遍历

//二叉树的后序遍历
void postorder(node* root)
{
	if (root == NULL)
		return;
	postorder(root->lchild);
	postorder(root->rchild);
	printf("%d", root->data);
}

二叉树的层序遍历

queue<node*>q;//如果声明的是node型,可能存在修改的是副本的情况
//二叉树的层序遍历
void LayerOrder(node* root)
{
	
	//添加到队列
	q.push(root);
	node* p;
	while (!q.empty())
	{
		p = q.front();
		q.pop();
		if (p != NULL)
		{
			printf("%d", p->data);
			if (p->lchild != NULL)
				q.push(p->lchild);
			if (p->rchild != NULL)
				q.push(p->rchild);
		}
	}
}

给定一棵二叉树的先序遍历序列和中序遍历序列,重建这棵树

//给定一棵二叉树的先序遍历序列和中序遍历序列,重建这棵树
int pre[];
int in[];
node* create(int preL, int preR, int inL, int inR)
{
	if (preL > preR)
	{
		return NULL;
	}
	//在中序中找到根的位置,然后计算出来左子树的个数和右子树的个数
	node* root =newNode(pre[preL]);//根结点
	//在中序中找到根的位置
	int i = inL
	for (; i <= inR; i++)
	{
		if (pre[preL] == in[i])
		{
			break;
		}
	}
	//左子树个数:i-inL
	//右子树个数:inR-i
	root->lchild = create(preL + 1, preL + i - inL, inL, i - 1);
	root->rchild = create(preR + i - inR + 1, preR, i + 1, inR);
	return root;
}
原文地址:https://www.cnblogs.com/code-fun/p/15226071.html