The tree data structure implemented (Tree) and Basic Operation

The definition of the tree

FIG tree is a data structure that is n (n> = 0) consisting of a finite set of nodes having a hierarchical relationship. We call it the "tree" because it looks like an upside down tree, which means that it is the root upward, downward and leaves.
Here Insert Picture Description

typedef struct BTree	//二叉树
{
	int val;
	struct BTree* rigth;
	struct BTree* left;
}BTree, *BTreePtr;

Creation and destruction of the tree

Recursive algorithm, you can easily create and destroy a tree.

TreeNode* CreateTree()
{
	int input = 0;
	scanf_s("%d", &input);

	TreeNode* t;

	if (input != 0)
	{
		t = (TreeNode*)malloc(sizeof(TreeNode));
		t->val = input;

		printf("\n%d的左孩子:\n", t->val);
		t->left = CreateTree();
		printf("\n%d的有孩子:\n", t->val);
		t->left = CreateTree();
	}
	else
	{
		return NULL;
	}

	return t;
}
void DestroyBTree(BTree* t)
{
	if (!t)
		return;

	BTree* left = t->left;
	BTree* rigth = t->rigth;
	free(t);
	t = NULL;
	DestroyBTree(left);
	DestroyBTree(rigth);
}

Traversing the tree

Preorder (Preorder)

Root -> left child -> right child.

void PreorderTraverseBTree(BTree* tree)
{
	if (!tree)
		return;
	printf("%d\t", tree->val);

	PreorderTraverseBTree(tree->left);
	PreorderTraverseBTree(tree->rigth);
}

Inorder traversal (Inorder)

Left child node -> root -> right child

void inorderBTree(BTree* tree)
{
	//递归出口
	if (!tree)
		return;

	inorderBTree(tree->left);
	printf("%d\t", tree->val);
	inorderBTree(tree->rigth);
}

Postorder (postorder)

Left child node -> right child -> root

void postorderBTree(BTree* tree)
{
	if (!tree)
		return;
	postorderBTree(tree->left);
	postorderBTree(tree->rigth);
	printf("%d\t", tree->val);
}

References Baidu Encyclopedia

Published 19 original articles · won praise 2 · Views 2530

Guess you like

Origin blog.csdn.net/SC_king/article/details/105203212