The creation of binary tree and its correlation algorithm __ Data Structure Basics

Source: Internet
Author: User
Tags assert

Binary tree is a very important data structure, it is the basis of the branch structure, today I will write a blog to describe its related algorithms and the two-fork tree creation process.

1: Two fork Tree creation:

There are several ways to create the sequence, the first three kinds are based on the traversal of the binary tree.

(1): First order creation

The first order creation is to create the root node first, then create its Saozi right subtree, we can use the recursive method, because the binary tree itself is based on the recursive algorithm.

(2): In order and after the following creation:

Understand the preface to create a two-tree way, in the preface and subsequent we can also analogy out, the so-called pre-post, is to create the order of the root node.

(3): Sequence Traversal and creation:


The above pictures reflect the sequence traversal process, the sequence traversal is based on the queue, first, if a binary tree is not empty, let the root node team, if the root node left subtree after the right subtree is not empty, then the root node out and print the value of its data field, left and right subtree (who is not empty who team), Then it's a recursive process.

The visible sequence traversal is a traversal process from top to bottom, from left to right.

So we can also create a binary tree in sequence: first create the root node, and if the left and right children of the root node do not point to the virtual node, create the Saozi right subtree, which is also created recursively.


Binary Tree Code:


function file bittree.c:

#include "Bittree.h" #include <stdio.h> #include <stdlib.h> #include <assert.h> tree *creat (tree* root
	, tree* (*ptree) (tree *root)) {root = Ptree (root);
return root;
	The tree *tier_creat (tree* root)/sequence creates two-forked trees root as the root node {subtree *s = NULL;
	DataType data = 0;       Tree *tree_arr[max] = {0};                     Creates a queue int front = 1 that stores a binary tree node;                      Front is the queue pointer initial value int rear = 0; Rear for the end of the queue the pointer is printf ("The layer creates a two-fork tree, 1 represents the virtual node,-2 indicates the end.")
	\ n ");
	scanf ("%d", &data);
		while (data!=-2) {s = NULL;
			if (data!=-1) {s = (tree*) malloc (sizeof (tree) * 1);
			S->data = data;
			S->lchild = NULL;
	    S->rchild = NULL;
		} rear++;           Tree_arr[rear] = s;      The parent node join the IF (rear = 1) root = s; If rear is the team head pointer, the root node of the two-fork tree stored in its queue else {if (Tree_arr[rear] && s)//children and parents are not virtual nodes {if (rear% 2 = 0        ) Tree_arr[front]->lchild = s; The new node is the left child if (rear% 2 = 1) {Tree_arr[front]->rchild = s;   The new node is the right child front++;
    If it is at this time rear refers to the right child, then out of the team, the next node into the team}} scanf ("%d", &data);
return root;
	Tree *dlr_creat (tree* root)//preface creates two-fork trees {printf ("with 1 means null pointer field to 2 to end the creation process \ n");
	root = NULL;
	int data = 0;
	printf ("Please enter data:");
    scanf ("%d", &data);
    if (data = = 1) return NULL;
	Root = (tree*) malloc (sizeof (tree) * 1); if (root = = NULL) {printf ("Create failed.")
			\ n ");
		 Exit (Exit_failure);
	 } root->data = data;
     Root->lchild=dlr_creat (Root->lchild);
     Root->rchild = Dlr_creat (root->rchild);
return root;
	Tree *ldr_creat (tree* root)//In order to create two fork trees {printf ("1 for the pointer field is NULL, 2 for the end of the creation process \ n");
	root = NULL;
	int data = 0;
	printf ("Please enter data:");
	scanf ("%d", &data);
	if (data = = 1) return NULL;
	Root->lchild = Dlr_creat (root->lchild);	
	Root = (tree*) malloc (sizeof (tree) * 1); if (root = = NULL) {printf ("Create failed.")
		\ n ");
	Exit (Exit_failure);
	} root->data = data;
	Root->rchild = Dlr_creat (root->rchild);return root;
	Tree *rld_creat (tree* root)//sequence creation two fork trees {printf ("1" indicates that the pointer field is null and 2 is the end of the creation process \ n);
	root = NULL;
	int data = 0;
	printf ("Please enter data:");
	scanf ("%d", &data);
    if (data = = 1) return NULL;
	Root->lchild = Dlr_creat (root->lchild);	
	Root->rchild = Dlr_creat (root->rchild);
	Root = (tree*) malloc (sizeof (tree) * 1); if (root = = NULL) {printf ("Create failed.")
		\ n ");
	Exit (Exit_failure);
	} root->data = data;
return root;
	} void Print_tree (Tree *root, Void (*ptree))//traversal of binary trees {assert (root); if (root = = null) {printf ("Tree is an empty tree.")
		\ n ");
	Return
		else {ptree (root);
	printf ("\ n");
	    } void Dlr_print (tree *root)//first-order traversal binary trees {if (root!= NULL) {printf ("%d", root->data);
	    Dlr_print (Root->lchild);
	Dlr_print (Root->rchild);

} return;
		} void Ldr_print (tree *root)//In-sequence traversal binary trees {if (root!= NULL) {dlr_print (root->lchild);
		printf ("%d", root->data);
	Dlr_print (Root->rchild);
} return; } void Rld_print (tree *root)//sequence traversing the binary tree {if (root!= NULL) {dlr_print (root->lchild);
		Dlr_print (Root->rchild);
	printf ("%d", root->data);
} return;
	} void Tie_print (tree *root)/sequence traversal binary trees {tree* Arry[max] = {0};
	int rear = 1;
	int front = 0; if (root = = null) {printf ("Binary tree is empty.")
		\ n ");
	Return                    else {arry[0] = root;
		If the binary tree is not empty, the root node is queued first.
				while (front < rear)//Loop condition queue Non-empty {if (Arry[front]) {printf ("%d", arry[front]->data);
				arry[rear++] = arry[front]->lchild;
				arry[rear++] = arry[front]->rchild;
			front++;
			else {front++;
	{}}} int Deep_tree (tree *root)//Find the depth of the binary trees {assert (root);
	int left = 0;
	int right = 0;
	int deep = 0;             if (root!= NULL) {left=deep_tree (root->lchild);          To find the left subtree depth right = Deep_tree (Root->rchild); Find right subtree depth deep = left > right-hand?
	(left + 1): (right + 1);
return deep; int Node_du (tree *root)//Ask for a sectionThe degree of the point {assert (root);
	int ret = 0;
	if (root = NULL) return 0;
		else {if (root->lchild!= NULL) ret++;
		if (root->rchild!= NULL) ret++;
	return ret;
	{Tree_node (tree *root) {assert (root);
	int ret = 0;
	if (root = NULL) return 0;
	if (Root->lchild = = Null&&root->rchild = NULL)//leaf node return 1;
	RET =1+ Tree_node (root->lchild) + Tree_node (root->rchild);
return ret;
	} tree* Search_node (tree *root, datatype data)//Lookup node {assert (root) with data value;
	Tree *p=null; if (root = = null) {printf ("Tree is an empty tree.")
		\ n ");
	return NULL;
		else {if (Root->data = = data) return root;
			if (root->lchild!= NULL) {p = Search_node (root->lchild,data);
		if (P!= NULL) return p;
			} if (Root->rchild!= NULL) {p = Search_node (root->rchild,data);
		if (P!= NULL) return p;   return NULL;
	Failed to find return null}} void Deal_tree (tree *root)//Free memory {assert (root); if (root = = NULL) return;
	Deal_tree (Root->lchild);
	Deal_tree (Root->rchild);
	Free (root);
root = NULL; }
Header file Bittree.h

#ifndef __bittree_h__ #define __BITTREE_H__ #define _CRT_SECURE_NO_WARNINGS #define MAX typedef int datatype;
	typedef struct BITTREE {datatype data;
	struct Bittree *lchild;

struct Bittree *rchild;
}tree;
	typedef struct {datatype Elem_data[max];
int length;
}tree_arry;   Tree *tier_creat (tree* root);    The sequence creates a two-fork tree root as the root node of the *dlr_creat (tree* root);    First order to create two-fork tree *ldr_creat (tree* root);    In order to create a two-fork tree *rld_creat (tree* root);     After the creation of the two-fork Tree *creat (tree* root,tree* (*ptree) (Shu *root));  Create a two-fork tree void Print_tree (*root, Void (*ptree) (Trees *root);      Traversing the binary tree void Dlr_print (*root);      First-order traversing binary tree void Ldr_print (*root);      The middle sequence traverses the binary tree void Rld_print (*root);      Subsequent traversal of the binary tree void Tie_print (*root);       Sequence traversal binary tree int deep_tree (*root);          To find the depth of the binary tree int node_du (*root);       To find the degree int tree_node (tree *root) of a node;                To find the number of nodes in the tree tree* search_node (trees *root, datatype data);      The node void Deal_tree (tree *root) with the lookup value is data; Freeing memory #endif __bittree_h__
 

Test file test.c:

#include "Bittree.h" #include <stdio.h> #include <stdlib.h> void Init () {printf ("Creation of 1: two fork tree \ n");
	printf ("Traversal of 2: two fork tree \ n");
	printf ("3: two fork tree depth query \ n");
	printf ("Query of the degree of a node of a 4: two fork tree \ n");
	printf ("5: Empty the binary tree \ n");
printf ("0: Exit \ n");
	void Init_print () {printf ("0: Sequence traversal binary tree. \ n");
	printf ("1: First sequence traversal binary tree. \ n");
	printf ("2: Subsequent traversal of binary tree. \ n");
printf ("3: In sequence traversal binary tree. \ n");
	void Init_creat () {printf ("0: Sequence creation two fork tree. \ n");
	printf ("1: First preface to create two fork tree. \ n");
	printf ("2: Create two fork tree after sequence");
printf ("3: In order to create two fork tree. \ n");
	} void Test () {int ret;
	int key=0;
	int choose;
	DataType data=0;
	Tree *root = NULL;
	Tree *node = NULL;   tree* (*tree_c[4]) (tree *root) = {0};   The function pointer array holds the creation method of the two-fork Tree Void (*tree_p[4]) (*root) = {0};
	function pointer array to store two-fork Tree traversal mode tree_c[0] = tier_creat;
	TREE_C[1] = dlr_creat;
	TREE_C[2] = ldr_creat;
	TREE_C[3] = rld_creat;
	Tree_p[0] = Tie_print;
	TREE_P[1] = Dlr_print;
	TREE_P[2] = Ldr_print;
	TREE_P[3] = Dlr_print;
		while (1) {printf ("Please enter your choice:");
		scanf ("%d", &key); Switch (key) {case 0:printf ("PRogram over!!
			\ n ");
			Exit (Exit_failure);
		Break
			Case 1:init_creat ();
				Do {printf ("Please enter your choice:");
			scanf ("%d", &choose);
			while (choose <= 0 && Choose >= 3);
			Root = creat (root, tree_c[choose]);
		Break
			Case 2:init_print ();
				Do {printf ("Please enter your choice:");
			scanf ("%d", &choose);
			while (choose <= 0 && Choose >= 3);
			Print_tree (Root, tree_p[choose]);
		Break
			Case 3:ret = deep_tree (root);
			printf ("The depth of the binary tree is:%d\n", ret);
		Break
			Case 4:printf ("Please enter the data that you want to query the node to save:");
			scanf ("%d", &data);
			Node=search_node (root, data); if (node = NULL) {printf ("The node you are querying for does not exist.
				\ n ");
			Exit (Exit_failure);
			ret = Node_du (Node);
			printf ("The degree of data%d nodes is:%d\n", data, ret);
		Break
			Case 5:deal_tree (root); printf ("Empty success.")
			\ n ");
		Break
	int main () {Init ();
	Test ();
	System ("pause");
return 0; }

If the above description has related questions please everybody can point out, I mail: 597995302@qq.com

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.