【Data structure】Storage structure of binary tree and first/middle/post-order recursive traversal algorithm (C language)

1. Trees and Binary Trees

1.1 Basic concept of tree

A tree is a finite set T of n (n>=0) nodes. When n = 0, it is called an empty tree; when n>0, the set satisfies:
① There must be a specific node called root, which has no direct predecessor, but has zero or more direct rear drive.
② The remaining n-1 nodes can be divided into m (m>=0) disjoint finite sets T1, T2, T3,..., Tn, where Ti is another tree, called the subtree of the root. The root node of each subtree has one and only one immediate predecessor, but zero or more immediate successors.
tree representation(1) Node : includes a data element and several branch information pointing to other nodes.
(2) Degree of a node : The number of subtrees of a node is called the degree of this node.
(3) Leaf node : a node with a degree of 0, that is, a node without a successor, also called a terminal node .
(4) Branch nodes : nodes whose degree is not 0, also called non-terminal nodes .
(5) Node level : Defined from the root node, the level of the root node is 1, the direct successor level of the root is 2, and so on.
(6) Layer sequence numbering of nodes : Arrange the nodes in the tree into a linear sequence from the upper layer to the lower layer, and from left to right in the same layer, and assign consecutive natural numbers to them in turn.
(7) Degree of the tree : the maximum value of the degrees of all nodes in the tree.
(8)The height (depth) of the tree : the maximum value of the levels of all nodes in the tree.
(9) Ordered tree : In the tree T, if there is a sequence among the subtrees Ti, it is called an ordered tree.
(10) Forest : a collection of m (m>=0) mutually disjoint trees. Delete the root node of a non-empty tree, and the tree becomes a forest; otherwise, add a unified root node to the forest, and the forest becomes a tree.
(11) Isomorphism : For two trees, by appropriately renaming the nodes, the two trees can be completely equal (the corresponding nodes are equal, and the correlations between the corresponding nodes are also equal), then the two trees are called isomorphic.
(12) Child node : The direct successor of a node is called the child node of the node. For example, B and C are children of A.
(13) Parent node : The direct predecessor of a node is called the parent node of the node. For example, A is the parent of B and C.
(14) Brother nodes : Children nodes of the same parent node are called brother nodes. For example, H, I, and G are brothers to each other.
(15) Cousins : The node whose father is a brother or cousin is called a cousin node. For example, nodes E, G, and H are cousins ​​of each other.
(16) Ancestor node : The ancestor node of a node refers to all nodes on the path from the root node to the node. For example, the ancestors of node K are A, B, E.
(17) Descendant node : The direct successor and indirect successor of a node are called the descendant node of the node. For example, the descendants of node D are H, I, J, M.
(18) Seniors : Nodes whose layer number is smaller than this node are called the predecessors of this node. For example, nodes A, B, C, and D can all be called predecessors of node E.
(19) Descendents : Nodes whose layer number is greater than this node are called the descendants of this node. For example, nodes K, L, and M can all be called descendants of node E.

1.2 Basic concept of binary tree

A tree structure that satisfies the following two conditions is called a binary tree .
① The degree of each node is not greater than 2.
② The order of child nodes of each node cannot be reversed arbitrarily.
Therefore, each node of a binary tree can only contain 0, 1 or 2 children, and each child has left and right points. The child on the left is called the left child, and the child on the right is called the right child.
Full binary tree : A binary tree with depth k and (2^k) -1 nodes. In a full binary tree, each level of nodes is full, that is, each level of nodes has the maximum number of nodes.
Complete binary tree : a binary tree with a depth of k and n nodes, if the position numbers of its nodes 1-n are in one-to-one correspondence with the position numbers of nodes 1-n of a full binary tree of equal height, then it is a complete binary tree.
The nature of the binary tree Property
1 : There are at most 2^(i-1) nodes (i>=1) on the i-th layer of the binary tree.
Property 2 : A binary tree with a depth of k has at most (2^k) -1 nodes (k>=1).
Property 3 : For any binary tree T, if the number of terminal nodes is n0, and the number of nodes whose degree is 2 is n2, then n0=n2+1.
Property 4 : The depth of a complete binary tree with n nodes is ⌊log2 (n)⌋+1.
Property 5 : For a complete binary tree with n nodes, if all the nodes in the binary tree are numbered from 1 in order from top to bottom and from left to right, then for any node with the sequence number i, there is :
① If i = 1, then the node with serial number i is the root node and has no parent node; if i > 1, then the serial number of the parent node of the node with serial number i is ⌊i / 2⌋.
② If 2i>n, then the node with the serial number i has no left child; if 2i<=n, then the serial number of the left child of the node with the serial number i is 2i.
③ If 2i+1>n, then the node with the serial number i has no right child; if 2i+1<=n, then the serial number of the right child of the node with the serial number i is 2i+1.

2. Binary tree storage structure and traversal algorithm

2.1 Storage structure of binary tree

For any binary tree, each node has only one parent node (except the root) and has at most two children, so each node contains at least three fields: data field, left child field and right child field.
Binary tree node structureAmong them, the LChild field points to the left child of the node, the Data field records the information of the node, and the RChild field points to the right child of the node. The binary tree formed by this node structure is called a binary linked list.
binary linked list
the code

/*二叉树的链式存储结构*/
typedef char DataType;
typedef struct Node {
    
    
	DataType data;
	struct Node* LChild;
	struct Node* RChild;
}BiTNode, * BiTree;

2.2 Preorder, inorder and postorder traversal of binary tree

Pre-order traversal (DLR) operation process:
① Visit the root node;
② Traverse the left subtree in pre-order;
③ Traverse the right sub-tree in pre-order.
Inorder traversal (LDR) operation process:
① Traverse the left subtree in inorder;
② Visit the root node;
③ Traverse the right subtree in inorder.
Post-order traversal (LRD) operation process:
① Traverse the left subtree in post-order;
② Traverse the right sub-tree in post-order;
③ Visit the root node.
Binary tree traversalBinary tree traversal code

/*先序遍历二叉树(递归)*/
void PreOrder(BiTree bt) {
    
    
	if (bt != NULL) {
    
    
		printf("%c ", bt->data);		//输出结点值
		PreOrder(bt->LChild);			//先序遍历左子树
		PreOrder(bt->RChild);			//先序遍历右子树
	}
}

/*中序遍历二叉树(递归)*/
void InOrder(BiTree bt) {
    
    
	if (bt != NULL) {
    
    
		InOrder(bt->LChild);			//中序遍历左子树
		printf("%c ", bt->data);		//输出结点值
		InOrder(bt->RChild);			//中序遍历右子树
	}
}

/*后序遍历二叉树(递归)*/
void PostOrder(BiTree bt) {
    
    
	if (bt != NULL) {
    
    
		PostOrder(bt->LChild);			//后序遍历左子树
		PostOrder(bt->RChild);			//后序遍历右子树
		printf("%c ", bt->data);		//输出结点值
	}
}

2.3 Application of traversal algorithm

2.3.1 Create a binary tree stored in the form of a binary linked list (traversing the sequence in extended order)

/*建立二叉链表方式存储的二叉树(按扩展先序遍历序列)*/
void CreateBiTree(BiTree* bt) {
    
    
//'.'表示空子树
	char ch;
	ch = getchar();
	if (ch == '.')								//'.'表示空子树
		*bt = NULL;
	else {
    
    
		(*bt) = (BiTree)malloc(sizeof(BiTNode));
		(*bt)->data = ch;						//生成根结点
		CreateBiTree(&((*bt)->LChild));			//构造左子树
		CreateBiTree(&((*bt)->RChild));			//构造右子树
	}
}

2.3.2 Preorder traversal to output the leaf nodes in the binary tree

/*先序遍历输出二叉树中叶子结点*/
void PreOrderLeaf(BiTree bt) {
    
    
	if (bt != NULL) {
    
    
		if (bt->LChild == NULL && bt->RChild == NULL)
			printf("%c ", bt->data);			//输出叶子结点值
		PreOrderLeaf(bt->LChild);				//先序遍历左子树
		PreOrderLeaf(bt->RChild);				//先序遍历右子树
	}
}

2.3.3 Post-order traversal to count the number of leaf nodes

/*后序遍历统计叶子结点数目*/
int count = 0;
void LeafCount(BiTree bt) {
    
    
	if (bt != NULL) {
    
    
		LeafCount(bt->LChild);
		LeafCount(bt->RChild);
		if (bt->LChild == NULL && bt->RChild == NULL)
			count++;
	}
}

2.3.4 Post-order traversal to find the height of the binary tree

/*后序遍历求二叉树高度*/
int PostTreeDepth(BiTree bt) {
    
    
	int hl = 0, hr = 0, max;
	if (bt != NULL) {
    
    
		hl = PostTreeDepth(bt->LChild);
		hr = PostTreeDepth(bt->RChild);
		max = hl > hr ? hl : hr;
		return (max + 1);
	}
	else
		return 0;
}

2.3.5 Print binary tree in tree form

/*按树状打印二叉树*/
void PrintTree(BiTree bt, int nLayer) {
    
    
	if (bt == NULL)
		return;
	PrintTree(bt->RChild, nLayer + 1);
	for (int i = 0; i < nLayer; i++)
		printf("  ");
	printf("%c\n", bt->data);					//按逆中序输出结点,用层深决定的左右位置
	PrintTree(bt->LChild, nLayer + 1);
}

2.4 Complete implementation code of binary tree operation

/*二叉树的存储结构及基本运算*/

# include<stdio.h>
# include<malloc.h>
# define TRUE 1
# define FALSE 0

/*二叉树的链式存储结构*/
typedef char DataType;
typedef struct Node {
    
    
	DataType data;
	struct Node* LChild;
	struct Node* RChild;
}BiTNode, * BiTree;

BiTree bt;

/*建立二叉链表方式存储的二叉树(按扩展先序遍历序列)*/
void CreateBiTree(BiTree* bt) {
    
    
//'.'表示空子树
	char ch;
	ch = getchar();
	if (ch == '.')									//'.'表示空子树
		*bt = NULL;
	else {
    
    
		(*bt) = (BiTree)malloc(sizeof(BiTNode));
		(*bt)->data = ch;							//生成根结点
		CreateBiTree(&((*bt)->LChild));				//构造左子树
		CreateBiTree(&((*bt)->RChild));				//构造右子树
	}
}

/*先序遍历二叉树(递归)*/
void PreOrder(BiTree bt) {
    
    
	if (bt != NULL) {
    
    
		printf("%c ", bt->data);				//输出结点值
		PreOrder(bt->LChild);					//先序遍历左子树
		PreOrder(bt->RChild);					//先序遍历右子树
	}
}

/*中序遍历二叉树(递归)*/
void InOrder(BiTree bt) {
    
    
	if (bt != NULL) {
    
    
		InOrder(bt->LChild);					//中序遍历左子树
		printf("%c ", bt->data);				//输出结点值
		InOrder(bt->RChild);					//中序遍历右子树
	}
}

/*后序遍历二叉树(递归)*/
void PostOrder(BiTree bt) {
    
    
	if (bt != NULL) {
    
    
		PostOrder(bt->LChild);					//后序遍历左子树
		PostOrder(bt->RChild);					//后序遍历右子树
		printf("%c ", bt->data);				//输出结点值
	}
}

/*先序遍历输出二叉树中叶子结点*/
void PreOrderLeaf(BiTree bt) {
    
    
	if (bt != NULL) {
    
    
		if (bt->LChild == NULL && bt->RChild == NULL)
			printf("%c ", bt->data);			//输出叶子结点值
		PreOrderLeaf(bt->LChild);				//先序遍历左子树
		PreOrderLeaf(bt->RChild);				//先序遍历右子树
	}
}

/*后序遍历统计叶子结点数目*/
int count = 0;
void LeafCount(BiTree bt) {
    
    
	if (bt != NULL) {
    
    
		LeafCount(bt->LChild);
		LeafCount(bt->RChild);
		if (bt->LChild == NULL && bt->RChild == NULL)
			count++;
	}
}

/*后序遍历求二叉树高度*/
int PostTreeDepth(BiTree bt) {
    
    
	int hl = 0, hr = 0, max;
	if (bt != NULL) {
    
    
		hl = PostTreeDepth(bt->LChild);
		hr = PostTreeDepth(bt->RChild);
		max = hl > hr ? hl : hr;
		return (max + 1);
	}
	else
		return 0;
}

/*按树状打印二叉树*/
void PrintTree(BiTree bt, int nLayer) {
    
    
	if (bt == NULL)
		return;
	PrintTree(bt->RChild, nLayer + 1);
	for (int i = 0; i < nLayer; i++)
		printf("  ");
	printf("%c\n", bt->data);					//按逆中序输出结点,用层深决定的左右位置
	PrintTree(bt->LChild, nLayer + 1);
}

int main() {
    
    
	printf("树的创建:");
	CreateBiTree(&bt);

	printf("先序遍历:");
	PreOrder(bt);

	printf("\n中序遍历:");
	InOrder(bt);

	printf("\n后序遍历:");
	PostOrder(bt);

	printf("\n叶子结点:");
	PreOrderLeaf(bt);

	LeafCount(bt);
	printf("\n叶结点数:%d", count);

	printf("\n树的高度:%d", PostTreeDepth(bt));

	printf("\n树状打印:\n");
	PrintTree(bt, 0);
	return 0;
}

2.5 Running results

operation result
Reference: Geng Guohua "Data Structure - Described in C Language (Second Edition)"

For more data structure content, follow my "Data Structure" column : https://blog.csdn.net/weixin_51450101/category_11514538.html?spm=1001.2014.3001.5482

Guess you like

Origin blog.csdn.net/weixin_51450101/article/details/122742243