括号二叉树建立(二叉树)

#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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值