Recently in the Leetcode do problem, the binary tree error when bad troubleshooting, so I wrote a function, the pre-sequence traversal format string into a binary tree.
Shaped like "ab#d# #C # #" String, "#" indicates that the child node is empty, the algorithm is as follows:
1. Current node-in-Stack push (s,t)
2. Out of Stack: Pcur=pop (s), judging the current character
A not equal to ' # ', Apply for new node pnew and assign to pcur left or right child, when right child will mark the true, pcur into the stack, pnew into the stack
b equals ' # ', if present for left child, left child to place null,pcur into stack;
Currently the right child, the right child is empty, the parent node is out of the stack. If Pcur is the left child of the parent node, stop looking, otherwise save the parent node as the current node and continue looking.
The code is as follows:
TreeNode *creat_tree (Char*str) { if(0= = strlen (str))returnNULL; TreeNode*t = (TreeNode *)malloc(sizeof(TreeNode)); TreeNode*pcur = NULL, *pnew =NULL; Stack*s =init_s (); BOOLLeft_child =true; T->data = *str; Push (S,T); while(' /'!= *++str) {Pcur=pop (s); printf ("pcur->data:%c, val:%c\n", pcur->data,*str); if('#'!= *str) {pnew= (TreeNode *)malloc(sizeof(TreeNode)); Pnew->data = *str; if(left_child) {pcur->lchild =pnew; } Else{pcur->rchild =pnew; Left_child=true;//the next value to be put on the left child} push (S,pcur); //parent node into the stackPush (s,pnew);//The new node is the next parent . } Else{ if(left_child) {pcur->lchild =NULL; Left_child=false;//no left child, next turn to right childPush (S,pcur);//current node into the stack, next turn to right child } Else{pcur->rchild = NULL;//No right child while( !Empty_stack (s)) {pnew= Pop (s);//Remove parent Node if(Pcur! = pnew->lchild) {//determine if Pcur is the left childPcur = pnew;//If not , the parent node already has 2 children}//continue searching until the parent node has only left child Else{push (s,pnew); //node into the stack, next turn to right child Break; }} printf ("Right end\n"); } } } returnt;}
Test the binary tree:
voidPreordertraverse (TreeNode *t) { //printf ("in preordertraverse\n"); if(NULL = = t)return; printf ("%c",t->data); Preordertraverse (t-lchild); Preordertraverse (t-rchild);}voidInordertraverse (TreeNode *t) { if(NULL = = t)return; Inordertraverse (t-lchild); printf ("%c",t->data); Inordertraverse (t-rchild);}voidPostordertraverse (TreeNode *t) { if(NULL = = t)return; Postordertraverse (t-lchild); Postordertraverse (t-rchild); printf ("%c",t->data);}intMain () {TreeNode*t =NULL; CharStr[] ="abdh#k## #E # #CFI # # # #G #j##"; T=Creat_tree (str); Preordertraverse (t); printf ("\ n"); Inordertraverse (t); printf ("\ n"); Postordertraverse (t); printf ("\ n"); CharStr2[] ="ab# #C # #"; T=Creat_tree (STR2); Preordertraverse (t); printf ("\ n"); Inordertraverse (t); printf ("\ n"); Postordertraverse (t); printf ("\ n");}
Output:
Abdhkecfigj
Hkdbeaifcgj
Khdebifjgca
Abc
Bac
Bca
C format string to binary tree