Algorithm learning, algorithm Learning Website
Tree traversal
These three traversal methods are actually very simple, for example:
a / \b c
This is an example of how the three are traversed.
The following are recursive methods, non-recursive method please refer to my another blog: http://blog.csdn.net/alps1992/article/details/38308285
struct TreeNode;typedef TreeNode* Node;typedef int EleType;struct TreeNode{ Node lchild; Node rchild; EleType data;};
First-order traversal
First traverse, that is, traverse from top to bottom, from left to right, when one is met, the above example traversesSequenceThat is:a b c
The recursive code is as follows:
void PreOrderTree(Node node){ if (node != NULL) { printf("%d\n",node->data); PreOrderTree(node->lchild); PreOrderTree(node->rchild); }}
Sequential Traversal
TheSequence:b a cIn fact, the middle-order traversal is to traverse from left to right, first find the leftmost, and then find its right child. If not, find the father, output, and finally output the right brother.
The Code is as follows:
}void InOrderTree(Node node){ if (node != NULL) { InOrderTree(node->lchild); printf("%d\n",node->data); InOrderTree(node->rchild); }}
Post-order traversal
TheSequence:a c bIn fact, the post-order traversal is to output the father of the Middle-order traversal after the right brother of the father.
The Code is as follows:
<pre name="code" class="cpp">void AfterPreOrderTree(Node node){ if (node != NULL) { AfterPreOrderTree(node->lchild); AfterPreOrderTree(node->rchild); printf("%d\n",node->data); }}