部分代码参考于:数据结构与算法 二叉树链式存储与括号表示法的相互转换
#include<iostream>
#include<stdlib.h>
using namespace std;
struct TreeNode {//树节点
char data;//数据域
struct TreeNode *Lchild;//左孩子结点
struct TreeNode *Rchild;//右孩子结点
};
void CreateBTNode(TreeNode *&root, char *str) {//创建二叉链
TreeNode *st[100] = {0}, *p;//栈st存放要操作的结点,p指向新节点
int top = -1;//栈顶
int flag = 0;//左右孩子flag
while (*str) {//指针解引用
switch (*str) {
case '(':
st[++top] = p;//遇到字符'(',将新节点进栈,合法的字符串里面,'('前面肯定会有节点字符
flag = 1;//标志下一个节点处理为当前节点的左孩子
break;
case ')':
--top;//遇到字符')'表示当前节点处理完毕,将其出栈
break;
case ',':
flag = 2;//标志下一个节点处理为当前节点的右孩子
break;
default://遇到结点值
p = (TreeNode *) malloc(sizeof(TreeNode));//节点字符,申请新节点
p->data = *str;//将数据域设置为当前字符
p->Lchild = NULL;//指针置空
p->Rchild = NULL;//指针置空
if (root == NULL) {//如果根节点为空,将新节点作为根结点
root = p;
} else {
switch (flag) {//根据flag值将新节点设置为当前操作节点的左孩子或右孩子
case 1:
st[top]->Lchild = p;
break;
case 2:
st[top]->Rchild = p;
break;
}
}
break;
}
++str;
}
}
void PrintBTNode(TreeNode *root) {//打印二叉链
if (root != NULL) {
cout << root->data;
if (root->Rchild != NULL || root->Lchild != NULL) {
cout << "(";
PrintBTNode(root->Lchild);//递归处理左子树
if (root->Rchild != NULL)
cout << ",";
PrintBTNode(root->Rchild);//递归处理右子树
cout << ")";
}
}
}
TreeNode *FindNode(TreeNode *root, char ch) {
TreeNode *p;
if (root == NULL)
return NULL;
else if (root->data == ch)
return root;
else {
p = FindNode(root->Lchild, ch);
if (p != NULL)
return p;
else
return FindNode(root->Rchild, ch);
}
}
TreeNode *LchildNode(TreeNode *root) {//返回*root结点的左孩子结点的指针
return root->Lchild;
}
TreeNode *RchildNode(TreeNode *root) {//返回*root结点的右孩子结点的指针
return root->Rchild;
}
int BTNodeDepth(TreeNode *root) {//求二叉链的高度
if (root == NULL)
return 0;
else {
int Lchild = BTNodeDepth(root->Lchild);//求左子树的高度
int Rchild = BTNodeDepth(root->Rchild);//求右子树的高度
return Lchild > Rchild ? (Lchild + 1) : (Rchild + 1);
}
}
void DestoryBTNode(TreeNode *&root) {//销毁二叉链
if (root == NULL)
return;
else {
DestoryBTNode(root->Rchild);
DestoryBTNode(root->Lchild);
free(root);
root = NULL;
}
}
int main() {
char str[] = "A(B(D(,G)),C(E,F))";
TreeNode *root = NULL;
TreeNode *p = NULL;
char ch = 'D';
CreateBTNode(root, str);
PrintBTNode(root);
cout << endl;
p = FindNode(root, ch);
if (p != NULL)
cout << p << endl << p->data << endl;
p = NULL;
p = LchildNode(root);
if (p != NULL)
cout << p << endl << p->data << endl;
p = NULL;
p = RchildNode(root);
if (p != NULL)
cout << p << endl << p->data << endl;
p = NULL;
cout << "Depth = " << BTNodeDepth(root) << endl;
DestoryBTNode(root);
return 0;
}