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->L); top++; Root->r=build (ROOT->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->L); Postorder (ROOT->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