对于一棵二叉树,我们知道他是树的一种特殊情况,但二叉树在满足某些条件的情况下可以描述大部分树!
对于新学习树的同学,我就先引入树的一些概念:
一个树是由n个元素组成的有限集合,每个元素我们叫做节点(node),特定的节点,叫根节点或者树根(root)
一棵树至少是有一个节点的;其他概念我们在接下来的代码中会引入
这是不是很想一棵二叉树呢,其实二叉树的子节点只有1个,2个,或者没有,其余注意的地方会在下一篇中讲到
首先我们来讲一个怎么储存树
稍微简单点的方法 数组,称为父亲表示法
const int m=10;
struct node{
int data,parent;
};
node tree[m];
这个不推荐使用,因为效率低下
还有很多方法这里不一一赘述
下面给出主要实现代码
typedef struct BTNode *Position; typedef Position BTree; struct BTNode { char data; Position lChild, rChild; }; BTree CreateBTree(BTree bt, bool isRoot) { char ch; if (isRoot) printf("Root: "); fflush(stdin); scanf("%c", &ch); fflush(stdin); if (ch != '#') { isRoot = false; bt = new BTNode; bt->data = ch; bt->lChild = NULL; bt->rChild = NULL; printf("%c's left child is: ", bt->data); bt->lChild = CreateBTree(bt->lChild, isRoot); printf("%c's right child is: ", bt->data); bt->rChild = CreateBTree(bt->rChild, isRoot); } return bt; }下面给出一个中序遍历的代码,自己没有测试,但思路是正确的
#include<bits/stdc++.h>using namespace std;struct node{ node *lchild; node *rchild; char data;}bitreenode,*bitree;void createbitree(bitree &t){ char c; cin>>c; if("#"==c) t==NULL; else { t=new bitreenode; t->data=c; createbitree(t->lchild); createbitree(t->rchild); }}void pre(bitree t){ if(t) { cout<<t->data<<" "; pre(t->lchild); pre(t->rchild); }}int main(){ bitree t; createbitree(t); pre(t); return 0;}
转载于:https://www.cnblogs.com/647Z/p/7341341.html
相关资源:JAVA上百实例源码以及开源项目