重建二叉树和树的层次遍历

#include 
#include 
using namespace std;

#define NSIZ 1000

//利用队列的先进先出特性,从根节点开始入队,出队,输出节点值,左孩子不空,左孩子入队;右孩子不空,右孩子入队
//循环直到队列为空;

//树的前序遍历
int preOrder1[] = {10, 6, 4, 8, 14, 12, 16};
//树的中序遍历
int inOrder1[] =  {4, 6, 8, 10, 12, 14, 16};

typedef struct Node_
{
	Node_ *left, * right;
	int data;
}Node;

//先序遍历
void preOrder(Node * root)
{
	if (root == 0)
	{
		return;
	}
	printf("%d ", root->data);
	preOrder(root->left);
	preOrder(root->right);
}

//利用先序数组和中序数组重建二叉树
Node * RebuildTree(Node *& root, int preOrder[], int inOrder[], int pl, int pr, int il, int ir)
{
	int i = 0;

	for (i = il;i <= ir; ++i)
	{
		if (inOrder[i] == preOrder[pl])
		{
			break;
		}
	}

	int  k = i - il;
	if (i > ir)
	{
		root = 0;
		return root;
	}
	else 
	{
		root = new Node();
		root->data = inOrder[i];
	}

	root->left = RebuildTree(root->left, preOrder, inOrder, pl + 1, pl + k , il, i-1);
	root->right = RebuildTree(root->right, preOrder, inOrder, pl + k + 1, pr, i + 1, ir);
	return root;

}

//二叉树的层次遍历
void TreeBfs(Node * root)
{
	if (!root)
	{
		return ;
	}

	queue qu;
	qu.push(root);

	while(!qu.empty())
	{
		Node * cur = qu.front();
		qu.pop();
		printf("%d ", cur->data);

		if (cur->left)
		{
			qu.push(cur->left);
		}

		if(cur->right)
		{
			qu.push(cur->right);
		}

	}

}


int main()
{
	int arr[] = {0, 8, 6, 10, 5, 7, 9, 11};
	int len = sizeof(arr)/sizeof(arr[0]);

	Node * root =RebuildTree(root, preOrder1, inOrder1, 0, 6, 0, 6);

	printf("前序遍历:");
	preOrder(root);

	printf("\r\n层次遍历:");
	TreeBfs(root);
	return 0;
}


你可能感兴趣的:(c/c++,面试题目)