您的位置:首页 > 理论基础 > 数据结构算法

数据结构与算法6:二叉树的存储结构与遍历

2014-01-19 16:46 169 查看
1. 二叉树的存储结构
二叉树的存储结构主要有两种。相对一般的树而言,二叉树比较特殊,存储也相对更简单明确。二叉树也是最常用的树。
如果二叉树接近满,那么可以使用顺序存储,因为二叉树的特殊性质,我们根据位置可以直接推算出它在树中的位置。如果是一般的二叉树的话,最常用的的还是二叉链表,即每个节点有两个指针,分别指向左子树和右子树。

2. 二叉树的遍历
二叉树的遍历主要是前序、中序和后续三种方式。其中前序遍历实际上是深度优先遍历。不多说,上代码。都是递归方式实现。

#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
	int data;
	struct node* left;
	struct node* right;
} node;

void createBinaryTree(node* root)
{
	int input;
	scanf("%d", &input);
	if (input == -1)
	{
		root = NULL;
	}
	else
	{
		root = (node*)malloc(sizeof(node));
		*root->data = input;
		createBinaryTree(*root->left);
		createBinaryTree(*root->right);
	}
}

void firstRootVisit(node* root)
{
	if (root == NULL)
	{
		return;
	}
	else
	{
		printf("%d ", *root->data);
		firstRootVisit(*root->left);
		firstRootVisit(*root->right);
	}
}

void lastRootVisit(node* root)
{
	if (root == NULL)
	{
		return;
	}
	else
	{
		lastRootVisit(*root->left);
		lastRootVisit(*root->right);
		printf("%d ", *root->data);
	}
}

void middleRootVisit(node* root)
{
	if (root == NULL)
	{
		return;
	}
	else
	{
		middleRootVisit(*root->left);
		printf("%d ", *root->data);
		middleRootVisit(*root->right);
	}
}

int main()
{
	node* root;
	createBinaryTree(root);
	firstRootVisit(root);
	lastRootVisit(root);
	middleRootVisit(root);
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐