Tree creation and three traversal methods in Data Structures

Source: Internet
Author: User

I did not have a good grasp of this piece of knowledge, so I sorted it out. below isCode;

 

# Include <stdio. h> # include <malloc. h> typedef struct tree_node {char data; struct tree_node * lchild, * rchild;} bt_node; bt_node * tree; // create bt_node * creat_tree (bt_node * tree) {char C; C = getchar (); If (C = '*') {tree = NULL;} else {tree = (struct tree_node *) malloc (sizeof (struct tree_node); tree-> DATA = C; tree-> lchild = creat_tree (tree-> lchild ); tree-> rchild = creat_tree (tree-> rchild);} return (tree);} // traverse the root node void Visit_node (bt_node * tree) {printf (""); putchar (tree-> data); printf ("\ t ");} // preorder traversal void pre_tree (bt_node * tree) {If (! Tree) {return;} else {visit_node (tree); pre_tree (tree-> lchild); pre_tree (tree-> rchild );}} // traverse void mid_tree (bt_node * tree) in the middle order {If (! Tree) {return;} else {mid_tree (tree-> lchild); visit_node (tree); mid_tree (tree-> rchild );}} // post-order traversal void after_tree (bt_node * tree) {If (! Tree) {return;} else {after_tree (tree-> lchild); after_tree (tree-> rchild); visit_node (tree) ;}} int main () {printf ("Enter the tree node... \ n "); tree = creat_tree (tree); If (tree) {printf (" Forward traversal \ n "); pre_tree (tree ); printf ("\ n"); printf ("sequential traversal \ n"); mid_tree (tree); printf ("\ n "); printf ("sequential traversal \ n"); after_tree (tree); printf ("\ n");} printf ("\ n"); Return 0 ;}

 

 

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.