Linux与数据结构 2019-3-16上午

1.创建一棵二叉树

1.1 创建二叉树的主要步骤在于对左右节点的创建,我们首先静态创建一个二叉树

  • 1.首先创建一个结构体用来装树的节点,其次定义一个函数用来生成树;
#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
	int n_value;
	struct node* p_left;
	struct node* p_right;
}BinaryTree;

BinaryTree* CreateTree()
{
	BinaryTree* p_tree = NULL;
	p_tree = (BinaryTree*)malloc(sizeof(BinaryTree));

	// 创建根节点
	p_tree->n_value = 1;

	// 创建 根的左
	p_tree->p_left = (BinaryTree*)malloc(sizeof(BinaryTree));
	p_tree->p_left->n_value = 2;

	// 创建 根的左的左
	p_tree->p_left->p_left = (BinaryTree*)malloc(sizeof(BinaryTree));
	p_tree->p_left->p_left->n_value = 4;
	p_tree->p_left->p_left->p_left = NULL;
	p_tree->p_left->p_left->p_right = NULL;

	// 创建 根的左的右
	p_tree->p_left->p_right = (BinaryTree*)malloc(sizeof(BinaryTree));
	p_tree->p_left->p_right->n_value = 5;
	p_tree->p_left->p_right->p_left = NULL;
	p_tree->p_left->p_right->p_right = NULL;

	// 创建 根的右
	p_tree->p_right = (BinaryTree*)malloc(sizeof(BinaryTree));
	p_tree->p_right->n_value = 3;

	// 创建 根的右的左
	p_tree->p_right->p_left = (BinaryTree*)malloc(sizeof(BinaryTree));
	p_tree->p_right->p_left->n_value = 6;
	p_tree->p_right->p_left->p_left = NULL;
	p_tree->p_right->p_left->p_right = NULL;

	// 创建 根的右的右
	p_tree->p_right->p_right = NULL;

	return p_tree;
}

int main()
{
	BinaryTree* p_tree = NULL;
	p_tree = CreateTree();

	return 0;
}
  • 2.下断点我们进行调试,可以确定创建成功;

1.2 遍历一颗二叉树

  • 1.可以通过深度来遍历;深度遍历二叉树的方法有三种:前序遍历、中序遍历、后序遍历;
  • 2.可以通过广度来遍历;广度遍历二叉树;
  • 3.首先使用递归方式来进行前序遍历;
void PreorderTraversal(BinaryTree *p_tree)
{
	// 退出条件
	if(p_tree == NULL)return;

	// 根
	printf("%d ", p_tree->n_value);

	// 左
	PreorderTraversal(p_tree->p_left);

	// 右
	PreorderTraversal(p_tree->p_right);
}
  • 4.使用前序遍历得到的结果是: 1 2 4 5 3 6;
  • 5.使用递归方式来完成中序遍历;
void InorderTraversal(BinaryTree *p_tree)
{
	// 退出条件
	if(p_tree == NULL)return;

	// 左
	InorderTraversal(p_tree->p_left);

	// 根
	printf("%d ", p_tree->n_value);

	// 右
	InorderTraversal(p_tree->p_right);
}
  • 6.使用中序遍历得到的结果是: 4 2 5 1 6 3;
  • 7.使用递归方式完成后序遍历;
void LastorderTraversal(BinaryTree *p_tree)
{
	// 退出条件
	if(p_tree == NULL)return;

	// 左
	LastorderTraversal(p_tree->p_left);

	// 右
	LastorderTraversal(p_tree->p_right);

	// 根
	printf("%d ", p_tree->n_value);
}
  • 8.使用后序遍历得到的结果是: 4 5 2 6 3 1;

1.3 动态创建一个二叉树

  • 1.也需要用到递归的思想,我们要先为树节点申请空间来装树,再对左右进行处理;
void DynamicCreateTree(BinaryTree** pp_tree)
{
	int num;
	scanf("%d ", &num);

	// 处理左右节点
	if(num == 0)return;

	// 处理树节点
	*pp_tree = (BinaryTree*)malloc(sizeof(BinaryTree));
	(*pp_tree)->n_value = num;
	(*pp_tree)->p_left = NULL;
	(*pp_tree)->p_right = NULL;

	// 处理树节点的左右节点
	DynamicCreateTree(&((*pp_tree)->p_left));
	DynamicCreateTree(&((*pp_tree)->p_right));
}

猜你喜欢

转载自blog.csdn.net/weixin_42896619/article/details/88703840