[C++] Tree

Tree details

The difference and judgment between full binary tree and complete binary tree

The realization of binary tree (array form)

Detailed implementation of binary tree

Think about how to store non-linear data in a linear manner in the storage of

Insert picture description here
ordinary trees

Parental notation: It is
more convenient to find the parent node. The
Insert picture description here
first is the index of the element in the array, and the latter is the index of the parent node. The array storage may not be stored in accordance with A, B...F, G, and can be freely stored. But to record the index of the parent node, so that the structure of the tree can be drawn according to the array structure.
Insert picture description here

Child notation: It is
more convenient
Insert picture description here
to find the child nodes, and store the pointers of the child nodes later

Parent-child notation:
Insert picture description here
Binary tree notation:
Convert an ordinary tree into a binary tree for storage

Method: Try to ensure that the left pointer of any node points to its first child, and the right pointer points to its next sibling.
Insert picture description here
There must be no right subtree in this transformation

Forest storage: After
Insert picture description here
transformation:
Insert picture description here
any ordinary tree is transformed into a binary tree, and there is no right subtree. Use this feature to make other trees as its right subtree.

Traversal of binary tree

Preorder traversal

In-order traversal

Post-order traversal

Insert picture description here

All can be summarized into the above four situations.

Know the pre-middle order and find the post-order, know the middle and post-order and find the pre-order

Knowing two traversal sequences, find the original binary tree

Known first order and middle order find later order

Example 1:
First order: ABCDEFGH
Middle order: BDCEAFHG
Seeking second order: DECBHGFA

Example 2:
First order: ABDGHCEFI
Middle order: GDHBAECIF
Seeking second order: GHDBEIFCA

Example 3:
First order: ABFDCLMN
Middle order: BFACDLNM
Seeking second order: FBCNMLDA

Example 4:
First order: MFLAQGBE
Middle order: FALGQMEB
Seeking second order: AGQLFEBM

Knowing the middle order and the latter order to find the first order

Middle order: BDCEAFHG
After order: DECBHGFA
Seek first order: ABCDEFGH

Idea: You can find the root node according to the preorder or the postorder, and then divide it into the left subtree and the right subtree according to the middle order. Cyclically

Guess you like

Origin blog.csdn.net/weixin_48180029/article/details/113540831