Build binary tree and recursive Traversal

Source: Internet
Author: User

# Include <stdio. h>
# Include <stdlib. h>
# Define elemtype char
// Node declaration, data field, left child pointer, right child pointer
Typedef struct bitnode {
Char data;
Struct bitnode * lchild, * rchild;
} Bitnode, * bitree;
// Create a binary tree in sequence
Bitree createbitree (){
Char ch;
Bitree T;
Scanf ("% C", & Ch );
If (CH = '#') t = NULL;
Else {
T = (bitree) malloc (sizeof (bitnode ));
T-> DATA = CH;
T-> lchild = createbitree ();
T-> rchild = createbitree ();
}
Return t; // return the root node
}
// Traverse Binary Trees in ascending order
Void preordertraverse (bitree t ){
If (t ){
Printf ("% C", T-> data );
Preordertraverse (t-> lchild );
Preordertraverse (t-> rchild );
}
}

// Sequential Traversal
Void inordertraverse (bitree t ){
If (t ){
Inordertraverse (t-> lchild );
Printf ("% C", T-> data );
Inordertraverse (t-> rchild );
}
}
// Post-order traversal
Void postordertraverse (bitree t ){
If (t ){
Postordertraverse (t-> lchild );
Postordertraverse (t-> rchild );
Printf ("% C", T-> data );
}
}
Void main (){
Bitree T;
T = createbitree (); // create
Printf ("\ npreorder: \ n ");
Preordertraverse (t); // output
Printf ("\ ninorder: \ n ");
Inordertraverse (t );
Printf ("\ npostorder: \ n ");
Postordertraverse (t );

}

Build binary tree and recursive Traversal

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.