Algorithm learning, algorithm Learning Website

Source: Internet
Author: User

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);    }}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.