#include <bits/stdc++.h>
using namespace std;
struct node{
char data;
node *lchild;
node *rchild;
};
void createBT(node *&root, string str){
stack<node*> st;
node *p;
int k;
root = NULL;
for(int i = 0; i < str.length(); i ++){
switch (str[i]){
case'(':
st.push(p); k = 1; break;
case')':
st.pop(); break;
case',':
k = 2; break;
default:
p = new node();
p->data = str[i];
p->lchild = p->rchild = NULL;
if(NULL == root){
root = p;
}else {
if(k == 1) st.top()->lchild = p;
else st.top()->rchild = p;
}
}
}
}
void destroyBT(node *&root){
if(root == NULL)return ;
else {
destroyBT(root->lchild);
destroyBT(root->rchild);
free(root);
}
}
node *findBT(node *root, int x){
node *p;
if(root == NULL)return NULL;
if(root->data == x)return root;
else {
p = findBT(root->lchild,x);
if(p != NULL)return p;
else return findBT(root->rchild,x);
}
}
node *lchildBT(node *&root){
return root->lchild;
}
node *rchildBT(node *&root){
return root->rchild;
}
int BTdepth(node *&root){
int lchilddep,rchilddep;
if(root = NULL)return 0;
else {
lchilddep = BTdepth(root->lchild);
rchilddep = BTdepth(root->rchild);
return (lchilddep>rchilddep)?(lchilddep+1):(rchilddep+1);
}
}
void dispBT(node *root){
if(root != NULL){
cout << root->data;
if(root->lchild!=NULL || root->rchild!=NULL){
cout << '(';
dispBT(root->lchild);
if(root->rchild != NULL) cout << ',';
dispBT(root->rchild);
cout << ')';
}
}
}
int main()
{
node *root;
string str = "A(B,C(D,E))";
createBT(root, str);//创建二叉树
destroyBT(root);//销毁二叉树b并释放空间
findBT(root,x);//在b中查找data值为x的结点,并返回该指针
lchildBT(root);//分别求二叉树中的*p的左孩子和右孩子
rchildBT(root);
BTdepth(root);//求二叉树的高度
dispBT(root);//以括号表示法输出一颗树
return 0;
}
括号二叉树建立(二叉树)
最新推荐文章于 2023-11-29 20:08:26 发布