Original: Step-by-Step writing algorithm (binary tree depth traversal)
"Disclaimer: Copyright, welcome reprint, please do not use for commercial purposes. Contact mailbox: feixiaoxing @163.com "
Deep traversal is a frequently encountered traversal method in software development. The commonly used traversal methods are as follows: (1) Pre-sequence traversal, (2) Middle sequence traversal, and (3) post-order traversal. According to recursive method, these three kinds of traversal methods are not difficult, in fact, the pre-sequence traversal is the root-left-right, the middle sequence traversal is left-root-right, subsequent traversal is left-right-root. The code is not complex to implement.
1) Pre-order traversal
void Preorder_traverse (tree_node* ptreenode) {if (Ptreenode) {printf ("%d", Ptreenode->data);p Reorder_traverse ( Ptreenode->left);p reorder_traverse (ptreenode->right);}}
2) Middle sequence traversal
void Inorder_traverse (tree_node* ptreenode) {if (Ptreenode) {inorder_traverse (ptreenode->left);p rintf ("%d", Ptreenode->data); Inorder_traverse (ptreenode->right);}}
3) post-traversal
void Afterorder_traverse (tree_node* ptreenode) {if (Ptreenode) {afterorder_traverse (ptreenode->left); afterorder_ Traverse (ptreenode->right);p rintf ("%d", Ptreenode->data);}}
4) An application of post-sequential traversal
The traversal methods above look simple, so what are their applications? We can take an example of a syntax tree in a programming language. For example, now we need to calculate a simple expression:
int m = 1 + 2 * 5-4/2;
So the syntax tree for this expression may be, where the semicolon at the end has been deleted.
Now, we're going to do a post-traversal of the above expression, which should look like this: M, 1, 2, 5, *, +, 4, 2,/、-、 =. So how do we calculate the expression of this output? It's not complicated, we just have to find that two consecutive numbers and a connected symbol can be calculated, and the order of the above expressions should be:
/** =* / * m -* / * + /* / \ / * 1 * 4 / * 2 5*/
A) m, 1, 2, 5, *, +, 4, 2,/、-、 =
b) m, 1, 10, +, 4, 2,/、-、 =
c) m, 11, 4, 2,/、-、 =
d) m, 11, 2 、-、 =
e) m, 9, =
f) m
Suggestions:
Although the above algorithm is relatively simple, but also relatively basic, but it is recommended that friends should be more practice and exercise.
Step-by-step write algorithm (binary tree depth traversal)