Data structure | The concept of binary tree and front, middle and back order traversal

Data structure | The concept of binary tree and front, middle and back order traversal

1. Tree concept and structure

The following content comes fromBaidu Encyclopedia

  • Binary tree is an important type of tree structure. The data structures abstracted from many practical problems are often in the form of binary trees. Even ordinary trees can be easily converted into binary trees. Moreover, the storage structure and algorithm of binary trees are relatively simple, so binary trees are particularly important. The characteristic of a binary tree is that each node can only have two subtrees at most, and they can be divided into left and right.
  • A binary tree is a set of n finite elements. The set is either empty or consists of an element called the root and two disjoint binary trees, called the left subtree and the right subtree respectively. It has sequence tree. When the set is empty, the binary tree is called an empty binary tree. In a binary tree, an element is also called a node.
  • Common tree structures include Binary Tree, Binary Search Tree, AVL tree, red-black tree, etc. Trees are used in a wide range of applications, such as index structures in databases, organization of file systems, priority queues in graph algorithms, etc.

Insert image description here

Note: In the tree structure, there cannot be intersection between subtrees, otherwise it will not be a tree structure

Insert image description here

1.1 Related concepts of trees

Tree is an important data structure that is widely used in computer science. A tree is a collection of nodes and edges, and nodes are connected through edges. One characteristic of a tree is that it is a hierarchical structure. The top node is called the root node (Root), the bottom node is called the leaf node (Leaf), and the middle node is called the internal node (Internal Node).

Insert image description here

Degree of node: The number of subtrees contained in a node is called the degree of the node; as shown above: A's is 6
Leaf node or terminal node: A node with degree 0 is called a leaf node; as shown in the figure above: nodes B, C, H, I... are leaf nodes
Non-terminal node or branch node: A node whose degree is not 0; As shown in the figure above: nodes such as D, E, F, G... are branch nodes
Parent nodes Or parent node: If a node contains child nodes, this node is called the parent node of its child node; As shown in the figure above: A is the parent node of B
Child node or child node: The root node of the subtree contained by a node is called the child node of the node; As shown in the figure above: B is the child node of A
Sibling nodes: Nodes with the same parent node are called sibling nodes; as shown in the figure above: B and C are sibling nodes
Degree of the tree: In a tree, the degree of the largest node is called the degree of the tree; as shown above: the degree of the tree is 6
Level of the node: From the definition of the root, the root is the 1st level, the root's child nodes are the 2nd level, and so on;
Height or depth of the tree: The maximum level of nodes in the tree; as shown in the picture above: the height of the tree is 4
cousin nodes: nodes whose parents are on the same level are cousins ​​of each other; as shown in the picture above : H and I are brother nodes of each other
The ancestor of the node: All nodes on the branches from the root to the node; as shown in the figure above: A is all nodes Ancestor
Descendants: Any node in the subtree rooted at a node is called a descendant of that node. As shown above: all nodes are descendants of A
Forest: A collection of m (m>0) disjoint trees is called a forest; < /span>

2. Representation of tree

  • There are many ways to represent a tree, the two main ones are: Child Representation and Parent Representation. In addition, for binary trees, there are more specific representation methods, such as array representation and link representation.

Child Representation:

  • In son notation, each node contains a pointer to all its child nodes. This representation is often used for multi-trees, where a node can have multiple child nodes.
    A
   / \
  B   C
 / \
D   E

Parent Representation:

  • In parent notation, each node contains a pointer to its parent node. This representation is commonly used for depth-first traversal of trees.
codeA -> NULL
B -> A
C -> A
D -> B
E -> B

2.2 Practical application of trees (representing the directory tree structure of the file system)

  • Tree structures are widely used in practice, and the directory tree structure representing a file system is one of the typical applications of tree structures. The directory structure of a file system can be naturally represented by a tree
  • For example, students who have studied Linux know that Linux is a tree structure, the root is< /span>/

Insert image description here

3. Binary tree concept and structure

  • Binary Tree is a special tree structure. Each node has at most two child nodes, called left child node and right child node. The structure and properties of binary trees make it widely used in computer science.

3.1 Basic concepts of binary trees

  • Node: The basic unit of the binary tree. Each node contains a data element and pointers to the left and right child nodes.
  • Root node (Root): The top node of the binary tree is the starting point of the tree and has no parent node.
  • Leaf node (Leaf): A node without child nodes is called a leaf node and is located at the end of the tree.
  • Internal Node: In addition to the root and leaf nodes, nodes with at least one child node are called internal nodes.
  • Child node (Child): The node directly below a node is called its child node.
  • Parent: The node directly above a node is called its parent node.
  • Sibling node (Sibling): Nodes with the same parent node are called sibling nodes.
  • Depth: The path length from a node to the root node is called the depth of the node, and the depth of the root node is 0.
  • Height: The path length from a node to its farthest leaf node is called the height of the node, and the height of the tree is the height of the root node.

3.2 Structure of binary tree:

a. Full Binary Tree:
  • In a full binary tree, every node except leaf nodes has two child nodes. All leaf nodes are on the same level.
        1
      /   \
     2     3
    / \   / \
   4   5 6   7
b. Complete Binary Tree:
  • In a complete binary tree, all levels are full except for the leaf nodes of the last level, and the leaf nodes of the last level are arranged to the left.
		1
      /   \
     2     3
    / \   /
   4   5 6
c. Binary Search Tree (BST):
  • In a binary search tree, the left subtree of each node is smaller than the node, and the right subtree is larger than the node, which makes operations such as search, insertion, and deletion very efficient.
	    4
      /   \
     2     6
    / \   / \
   1   3 5   7

4. Application of Binary Tree

  1. Searching and sorting: Binary search trees are used to implement fast searching and sorting operations.
  2. Expression tree: is used to represent mathematical expressions for easy evaluation.
  3. File system: is used to represent the hierarchical structure of file directories.
  4. Compiler: In the syntax analysis stage, a syntax tree (usually a binary tree) is used to represent the syntax structure of the program.
  5. Huffman tree: is used to build the optimal coding tree in data compression algorithms.
  6. Game tree: In game theory, a decision tree used to represent a game.

5. Properties of binary trees

  1. Each node has at most two child nodes: Each node has at most two child nodes, a left child node and a right child node.
  2. Each node has zero, one, or two children: This means that a node can be a leaf node (no children), have one child, or have two child node.
  3. The left and right subtrees are ordered: For a binary search tree (BST), the value of each node in the left subtree is less than the node's value, the value of each node in the right subtree is greater than the value of this node.
  4. Height of the tree: The height of the tree is the longest path from the root node to the deepest leaf node. The height of a binary tree with n nodes is at most n and at least log₂(n+1).
  5. The nodes at the last level are concentrated on the left: In a complete binary tree, the nodes at the last level are arranged from left to right, and missing positions will only appear on the far right.
  6. Full binary tree: A binary tree with height h and 2^h - 1 nodes is called a full binary tree.
  7. Complete binary tree: A binary tree with n nodes. If it is a full binary tree from the root node to the penultimate level, the nodes of the last level are all concentrated on the left side, then it is a complete binary tree.
  8. Node number: For a binary tree, each node can be numbered from top to bottom and from left to right, starting from 1. If a node is numbered i, then its left child node is numbered 2i, and its right child node is numbered 2i+1.

6. Storage structure of binary tree

6.1 Sequential storage structure

  • In sequential storage structures, arrays are used to represent binary trees. The specific method is to store the nodes of the binary tree in the array in order from top to bottom and from left to right. If the number of a node is i, then the number of its left child node is 2i, and the number of its right child node is 2i+1.

For example:

        1
       / \
      2   3
     / \ / \
    4  5 6  7
  • The corresponding sequential storage structure is:
[1, 2, 3, 4, 5, 6, 7]
  • The index of the array here starts from 1, the root node corresponds to index 1, and the relationship between the left child node and the right child node is arranged according to the rules of 2i and 2i+1.

Insert image description here

6.2 Chain storage structure

  • In the linked storage structure, each node points to its left child node and right child node through a pointer or reference. Such a storage structure is more intuitive and easier to implement. The definition of nodes is as follows:
struct TreeNode {
    
    
    int data; // 节点的数据
    TreeNode* left; // 指向左子节点的指针
    TreeNode* right; // 指向右子节点的指针
};
        1
       / \
      2   3
     / \ / \
    4  5 6  7

The left and right pointers of each node point to its left child node and right child node respectively. This storage structure is more intuitive, but may take up more memory space than the sequential storage structure.

Insert image description here

Insert image description here

typedef int BTDataType;
// 二叉链
struct BinaryTreeNode
{
    
    
	struct BinTreeNode* _pLeft; // 指向当前节点左孩子
	struct BinTreeNode* _pRight; // 指向当前节点右孩子
	BTDataType _data; // 当前节点值域
}
// 三叉链
struct BinaryTreeNode
{
    
    
	struct BinTreeNode* _pParent; // 指向当前节点的双亲
	struct BinTreeNode* _pLeft; // 指向当前节点左孩子
	struct BinTreeNode* _pRight; // 指向当前节点右孩子
	BTDataType _data; // 当前节点值域
}

6.3 Sequential structure and implementation of binary tree

  • Ordinary binary trees are not suitable for storage in arrays because there may be a lot of wasted space. A complete binary tree is more suitable for sequential structure storage. In reality, we usually store the heap (a kind of binary tree) using an array of sequential structure. It should be noted that the heap here and the heap in the virtual process address space of the operating system are two different things. One is the data structure and the other is the management in the operating system. An area of ​​memory is segmented.

Insert image description here

7. Implementation of binary tree chain structure

  • Before learning the basic operations of a binary tree, you need to create a binary tree first, and then you can learn its related basic operations. Since everyone currently does not have a deep enough understanding of the binary tree structure, in order to reduce everyone's learning cost, here we quickly create a simple binary tree manually and quickly enter the binary tree operation learning. When the binary tree structure is almost understood, we will go back to study the real binary tree. Creation method.

  • Let’s first review the concept of binary trees:

  1. empty tree
  2. Non-empty: The root node, the left subtree of the root node, and the right subtree of the root node.

Insert image description here

It can be seen from the concept that the definition of binary tree is recursive, so the basic operations of post-order are basically implemented according to this concept.

8. Binary tree traversal [Key points]

8.1 Preorder, inorder and postorder traversal

  1. Preorder Traversal (also known as preorder traversal) - the operation of accessing the root node occurs before traversing its left and right subtrees. To put it simply,the access sequence is 左子树 右子树
  2. Inorder Traversal - The operation of accessing the root node occurs during the traversal of its left and right subtrees (between). To put it simply, the access sequence is 左子树 右子树
  3. Postorder Traversal - The operation of accessing the root node occurs after traversing its left and right subtrees. To put it simply, the access sequence is 左子树 右子树

build a tree

BTNode* BuyTreeNode(int x)
{
    
    
	BTNode*node = (BTNode*)malloc(sizeof(BTNode));
	assert(node);

	node->data = x;
	node->left = NULL;
	node->right = NULL;

	return node;
}

BTNode* CreateTree()
{
    
    
	BTNode* node1 = BuyTreeNode(1);
	BTNode* node2 = BuyTreeNode(2);
	BTNode* node3 = BuyTreeNode(3);
	BTNode* node4 = BuyTreeNode(4);
	BTNode* node5 = BuyTreeNode(5);
	BTNode* node6 = BuyTreeNode(6);

	node1->left = node2;
	node1->right = node4;
	node2->left = node3;
	node4->left = node5;
	node4->right = node6;

	return node1;
}

Preorder traversal of binary tree

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

Inorder traversal of binary tree

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

Binary tree postorder traversal

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

test

int main()
{
    
    
	BTNode* root = CreateTree();

	printf("二叉树前序遍历:\n");
	BinaryTreePrevOrder(root);
	printf("\n");

	printf("二叉树中序遍历:\n");
	BinaryTreeInOrder(root);
	printf("\n");

	printf("二叉树后序遍历:\n");
	BinaryTreePostOrder(root);
	printf("\n");

	return 0;
}

Insert image description here

Guess you like

Origin blog.csdn.net/2201_76004325/article/details/134593170