[二叉樹] 先根遍歷歸遞演算法
阿新 • • 發佈:2019-01-09
#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; }