二叉树的部分操作:获取高度,获取结点数,交换每个结点的左、右子树
结构体如下
typedef struct btnode {
ElemType element;
struct btnode* lchild, *rchild;
}BTNode;
typedef struct binarytree{
BTNode* root;
}BinaryTree;
获取二叉树高度
调用函数 Heigt(BinaryTree t)
int getHeight(BTNode *root){
if(root==NULL){
return 0;
}
int leftheight=getHeight(root->lchild);
int rightheight=getHeight(root->rchild);
return max(leftheight, rightheight)+1;
}
int Height(BinaryTree t){
return getHeight(t.root);
}
获取二叉树结点数
调用函数 Number(BinaryTree t)
int getNumber(BTNode *root){
if(root == NULL)
return 0;
if(root->lchild == NULL && root->rchild == NULL)
return 1;
return 1 + getNumber(root->lchild) + getNumber(root->rchild);
}
int Number(BinaryTree t){
return getNumber(t.root);
}
交换一棵二叉树中每个结点的左、右子树
调用函数Change(BinaryTree t)
void Exchange(BTNode *root){
if(root==NULL){
return ;
}
BTNode *temp;
temp=root->lchild;
root->lchild=root->rchild;
root->rchild=temp;
Exchange(root->lchild);
Exchange(root->rchild);
}
void Change(BinaryTree *t){
Exchange(t->root);
}
第一次写,上述代码均已跑过,应该没有问题如有错误,欢迎指正,哈哈哈。