Algorithmic customs clearance village - how to use inorder and postorder to restore a binary tree

Preorder: 1 2 3 4 5 6 8 7 9 10 11 12 13 15 14
Inorder: 3 4 8 6 7 5 2 1 10 9 11 15 13 14 12
Postorder: 8 7 6 5 4 3 2 10 15 14 13 12 11 9 1

First look at the relevant definitions:
pre-order traversal: middle,
left, and right, so it can be determined that 1 is the root node. 12
Subsequent traversal: left and right, left 8 7 6 5 4 3 2, right 10 15 14 13 12 11 9

Here we can reach the approximate left and right positions of the elements.

first round

[3 4 8 6 7 5 2 ]1[10 9 11 15 13 14 12 ]
insert image description here

second round

Postorder + Inorder
Postorder: Left 8 7 6 5 4 3 2 Right 10 15 14 13 12 11 9
Postorder traversal determines that the root node on the left is 2, and the root node on the right is 9
According to the inorder, the left side of 2 can be determined The elements are 3 4 8 6 7 5, there is no right element, the left element of 9 is 10, and the right element is 11 15 13 14 12 [3 4 8 6 7 5]2 [10]9[11 15 13 14
12
]
insert image description here

third round

Through post-order traversal 8 7 6 5 4 3, the root node is 3
subsequent traversal 15 14 13 12 11, the root node is 11
in-order traversal, 3 has no left element, and there is a right element 4 8 6 7 5
in-order traversal, 11 has no Left element, right element 15 13 14 12
3[ 4 8 6 7 5]
11[15 13 14 12]
insert image description here

fourth round

Subsequent traversal 8 7 6 5 4 , the root is 4
Subsequent traversal 15 14 13 12 , the root is
8 6 7 5 to the right
of inorder 4 in 12, no left element 15 13 14 to the left of inorder 12, no right element
4 [8 6 7 5 】
【15 13 14】12
insert image description here

fifth round

Subsequence 8 7 6 5 root 5
follow-up 15 14 13 root 13
middle: 5 left 8 7 6
middle: 13 left 15 right 14
【8 7 6】5
【15】13【14】
insert image description here

sixth round

Rear: 8 7 6 root
6 in 8 6 7 left 8 right 7
insert image description here

total

insert image description here

Guess you like

Origin blog.csdn.net/qq_52843958/article/details/132023820