//文件名:exp7-1.cpp
#include
typedef char ElemType;
typedef struct node
{
ElemType data; //数据元素
struct node *lchild; //指向左孩子
struct node *rchild; //指向右孩子
} BTNode;
extern void CreateBTNode(BTNode *&b,char *str);
extern BTNode *FindNode(BTNode *b,ElemType x);
extern BTNode *LchildNode(BTNode *p);
extern BTNode *RchildNode(BTNode *p);
extern int BTNodeDepth(BTNode *b);
extern void DispBTNode(BTNode *b);
extern int BTWidth(BTNode *b);
extern int Nodes(BTNode *b);
extern int LeafNodes(BTNode *b);
extern void DestroyBTNode(BTNode *&b);
void main()
{ BTNode *b,*p,*lp,*rp;;
CreateBTNode(b,"A(B(D,E(H(J,K(L,M(,N))))),C(F,G(,I)))");
printf("二叉树的基本运算如下:\n");
printf(" (1)输出二叉树:");DispBTNode(b);printf("\n");
printf(" (2)H节点:");
p=FindNode(b,'H');
if (p!=NULL)
{ lp=LchildNode(p);
if (lp!=NULL)
printf("左孩子为%c ",lp->data);
else
printf("无左孩子 ");
rp=RchildNode(p);
if (rp!=NULL)
printf("右孩子为%c",rp->data);
else
printf("无右孩子 ");
}
printf("\n");
printf(" (3)二叉树b的深度:%d\n",BTNodeDepth(b));
printf(" (4)二叉树b的宽度:%d\n",BTWidth(b));
printf(" (5)二叉树b的节点个数:%d\n",Nodes(b));
printf(" (6)二叉树b的叶子节点个数:%d\n",LeafNodes(b));
printf(" (7)释放二叉树b\n");
DestroyBTNode(b);
}
见代码,二叉树的宽度,很奇葩,我的理解是隔了多少个结点,宽度就为多少.
#include
using namespace std;
struct node
{
char value;
node* left;
node* right;
node(char v):value(v),left(NULL),right(NULL){}
};
void ConnectTreeNodes(node* pParent, node* pLeft, node* pRight)
{
if(pParent)
{
pParent->left = pLeft;
pParent->right = pRight;
}
}
node* CreateTree()
{
node *pa=new node('a');
node *pb=new node('b');
node *pc=new node('c');
node *pd=new node('d');
node *pe=new node('e');
node *pf=new node('f');
node *pg=new node('g');
node *ph=new node('h');
node *pi=new node('i');
ConnectTreeNodes(pa,pb,pi);
ConnectTreeNodes(pb,pc,pf);
ConnectTreeNodes(pc,pd,pe);
ConnectTreeNodes(pi,pg,ph);
return pa;
}
int TreeHeight(node* root)
{
if(!root) return 0;
int left=TreeHeight(root->left);
int right=TreeHeight(root->right);
return 1+(left > right?left : right);
}
int TreeLeaves(node* root)
{
if(!root) return 0;
if(!root->left && !root->right)
return 1;
return TreeLeaves(root->left)+TreeLeaves(root->right);
}
int TreeWidth(node* root)
{
if(!root) return 0;
if(!root->left && !root->right)
return 1;
return TreeWidth(root->left)+TreeWidth(root->right)+1;
}
void TreeWalk(node* root)
{
if(!root) return ;
TreeWalk(root->left);
cout<value<<' ';
TreeWalk(root->right);
}
void main()
{
node* root=CreateTree();
TreeWalk(root);
int TreeHeigh=TreeHeight(root);
cout<int TreeLeave=TreeLeaves(root);
cout<int TreeWid=TreeWidth(root);
cout<}
什么是二叉树的基本算法?
算法是建立在应用的基础上的,没有明确的需求,对于数据结构,算法的设计恐怕也没什么根据