中跟遍历

编程入门 行业动态 更新时间:2024-10-24 22:28:27

中跟<a href=https://www.elefans.com/category/jswz/34/1771029.html style=遍历"/>

中跟遍历

// 先序(附带叶子标记)建树
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stack>
#include<string>
using namespace std;
struct node
{char data;node* lchild;node* rchild;
};
void buildtree(char* str,node* root)
{stack<node*> sta;int pos = 0;int len = strlen(str);node* tmp;root->data = str[pos++];root->lchild = NULL;root->rchild = NULL;sta.push(root);while(pos < len){while(true){node* nl = new node;nl->data = str[pos];nl->lchild = NULL;nl->rchild = NULL;if(str[pos]=='*'){free(nl);break;}sta.top()->lchild = nl;sta.push(nl);++pos;}tmp = sta.top();sta.pop();++pos;while(str[pos]=='*'){if(!sta.empty()){tmp = sta.top();sta.pop();}++pos;}if(pos >= len)break;node* nr = new node;nr->data = str[pos];nr->lchild = NULL;nr->rchild = NULL;sta.push(nr);tmp->rchild = nr;++pos;}return;
}
void visit_rootsecond(node* root)
{stack<node*> sta;bool _end = false;node* p;sta.push(root);while(!sta.empty()){p = sta.top();while(p){p = p->lchild;sta.push(p);}sta.pop();p = sta.top();printf("%c",p->data);p = p->rchild;sta.pop();if(p){sta.push(p);continue;}while(p==NULL){if(sta.empty()){_end = true;break;}p = sta.top();sta.pop();p = p->rchild;}if(!_end){sta.push(p);}}
}
int main()
{char* str = new char[100];gets(str);//printf("%s",str);node* root = new node;buildtree(str,root);return 0;
}

更多推荐

中跟遍历

本文发布于:2024-02-11 17:09:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1682183.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:遍历

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!