[二叉树] 先根遍历归递算法

来源:互联网 发布:计算机转金融知乎 编辑:程序博客网 时间:2024/05/17 19:16
 #include <iostream>using namespace std;struct Tree {int  data;Tree *lchild, *rchild;};// 建立二叉树以指针数组形式存放;Tree *Create() {Tree *p, *s[50], *t;int i, j, e;while (1) {// i 为数组编号,输入编号i;cin >> i;// 以 i 等于0 为结束标记;if (i == 0)break;else {cin >> e;p = new Tree();p->lchild = p->rchild = NULL;p->data = e;s[i] = p;// 若 i == 1 说明是根结点,t指向根结点;if (i == 1)t = p;else {// j 是i的父结点,i%2 == 0 说明是j的左结点,若不是说明是右结点;j = i/2;if (i%2 == 0)s[j]->lchild = p;else s[j]->rchild = p;}}}return t;}// 输出各个结点的数据;void Preordet(Tree *t) { if (t != NULL) {cout << t->data << "\t";Preordet(t->lchild );Preordet(t->rchild );}}int main() {Tree *s, *t;t = Create();Preordet(t);cout << endl;return 0;}