Establishment and traversal of binary tree

Source: Internet
Author: User

Establishment and traversal of binary tree in data structure experiment Time limit:1000ms Memory limit:65536k have questions? Dot here ^_^ The title describes a sequence of characters that is known to be entered by an ordinal sequence, such as abc,,de,g,,f,,, (where commas represent empty nodes). Please establish a two-fork tree and traverse the binary tree according to the sequence and order, and finally find out the number of leaf nodes and the depth of the two fork tree.

Enter a string that is less than 50 characters in length. Output output Total 4 lines:
The 1th line outputs the sequential traversal sequence;
The 2nd line outputs the sequential traversal sequence;
The number of leaf nodes is output in line 3rd;
The 4th row outputs the binary tree depth. Sample input
Abc,,de,g,,f,,,
Sample output
Cbegdfacgefdba35
Tips

#include <iostream> #include <cstdio> #include <cstring>using namespace Std;char head[200];int top,    Sum,deep;struct tree{Char c; Tree* L,*r;};    tree* creat () {tree* p;    P=new Tree;    p->l=null;    p->r=null; return p;} tree* Build (tree*root) {if (!head[top]| |    head[top]== ', ') return NULL;    Root=creat ();    root->c=head[top];    top++;    Root->l=build (ROOT-&GT;L);    top++;    Root->r=build (ROOT-&GT;R); return root;}        int inorder (tree* root,int ans) {if (!root) {if (ans>deep) {Deep=ans;    } return 0;    } if (!root->l&&!root->r) {sum++;    } inorder (root->l,ans+1);    printf ("%c", root->c); Inorder (root->r,ans+1);}    int postorder (tree* root) {if (!root) return 0;    Postorder (ROOT-&GT;L);    Postorder (ROOT-&GT;R); printf ("%c", Root->c);}    int main () {cin>>head;    Top=0;    sum=0;    Deep=0;    tree* Root=build (root);   Inorder (root,0); cout<<endl;    Postorder (root);    cout<<endl;    cout<<sum<<endl; Cout<<deep<<endl;}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Establishment and traversal of binary tree

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.