How to calculate the preorder traversal and intermediate order traversal of python binary tree
In this issue, the editor will bring you about how to calculate the preorder traversal and middle order traversal of the python binary tree. The article is rich in content and analyzes and describes for you from a professional point of view. I hope you can get something after reading this article.
Idea: when you see the algorithm of binary tree, the first thing that comes to mind is traversal.
Now that the preorder traversal and intermediate order traversal are given, I calculate the preorder traversal and intermediate order traversal of the left subtree, and the preorder traversal and intermediate order traversal of the right subtree each time.
Main program
Int len = pre.length
If (len = = 0) {
Return null
}
Else {
TreeNode tnode = new TreeNode (pre [0])
Int loc = getindex (pre [0], in)
Int [] preL = getsubarr (1, loc, pre); / / preorder traversal of the left subtree
Int [] preR = getsubarr (0, loc-1, in); / / the mid-order traversal of the left subtree is equal in length
Int [] inL = getsubarr (loc+1,len-1, pre); / / preorder traversal of the right subtree
Int [] inR = getsubarr (loc+1,len-1, in); / / the length of the middle order traversal of the right subtree is equal.
Tnode.left = getarr (preL, preR)
Tnode.right = getarr (inL, inR)
Return tnode
}
# A function that defines a given sequence and target value and finds the index of the target value in the sequence
Public int getindex (int target, int [] array) {
Int len = array.length
For (int iTuno; I < len; iTunes +) {
If (target = = array [I]
Return i
}
}
Define the start and end subscripts of a given array and give the corresponding fields for the array
Public int [] getsubarr (int start, int end, int [] arr) {
Int [] sub = new int [end-start+1]
For (int iTunes start; I