C/C++二叉樹的建立與遍歷
阿新 • • 發佈:2019-02-04
在建立二叉樹的時候,當節點為葉子節點,需要將葉子節點的兩個子節點輸入0,以0作為結束識別符號。
1.建立二叉樹的結構體
typedef struct tree* bintree;
typedef bintree position;
struct tree {
int data;
position lchild;
position rchild;
};
2.按照前序排序順序建立二叉樹
3.按照前序和中序遍歷二叉樹bintree creattree() { int ch; bintree t; cin >> ch; if (0 == ch) { t = NULL; } else { t = (struct tree*)malloc(sizeof(struct tree)); t->data = ch; t->lchild=creattree(); t->rchild=creattree(); } return t; }
void pre_display(bintree head) { if (head) { cout << head->data << ' '; pre_display(head->lchild); pre_display(head->rchild); } } void inorder_display(bintree head) { if (head) { inorder_display(head->lchild); cout << head->data << ' '; inorder_display(head->rchild); } }
主函式:
int main()
{
bintree head;
bintree p;
head = NULL;
p=creattree();
pre_display(p);
system("PAUSE");
}