```c++ TreeNode* BuildTree(char c[],int s,int e){ //当s==e时,数组只剩一个元素,而且必是操作数值 if(s==e){ TreeNode *node = new TreeNode; node->rChild = node->lChild = NULL; node->val = c[s]; return node; } //从后向前找+- 从后开始遍历纯粹是为了好看 for(int i=e;i>=s;i--){ if(c[i]=='+'||c[i]=='-'){ //这个+-做根节点 TreeNode *node = new TreeNode; node->lChild = node->rChild = NULL;//左右子置空 node->val = c[i];//将操作符赋值给该节点 node->lChild = BuildTree(c,s,i-1);//分开的左子树,s到i-1是+-号左边的那部分 node->rChild = BuildTree(c,i+1,e); //分开的右子树,i+1到e是+-号右边的内容 return node;//返回到上一级给左右子,或者给根 } } for(int j=s;j<=e;j++){ if(c[j]=='*'){ //没有+-后运算符*作根 TreeNode *node = new TreeNode; node->lChild = node->rChild = NULL; node->val = c[j]; node->lChild = BuildTree(c,s,j-1); node->rChild = BuildTree(c,j+1,e); return node; } } for(int j=e;j>=s;j--){ if(c[j]=='/'){ //没有+-后运算符/作根 //因为优先级问题从后面读起 TreeNode *node = new TreeNode; node->lChild = node->rChild = NULL; node->val = c[j]; node->lChild = BuildTree(c,s,j-1); node->rChild = BuildTree(c,j+1,e); return node; } } }将这段代码更改为 c 语言
时间: 2024-02-28 16:52:21 浏览: 138
c++的树结构
把代码中的 TreeNode* 替换为 struct TreeNode*,同时需要加上头文件和结构体定义,代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
char val;
struct TreeNode* lChild;
struct TreeNode* rChild;
};
struct TreeNode* BuildTree(char c[], int s, int e) {
//当s==e时,数组只剩一个元素,而且必是操作数值
if (s == e) {
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->rChild = node->lChild = NULL;
node->val = c[s];
return node;
}
//从后向前找+- 从后开始遍历纯粹是为了好看
for (int i = e; i >= s; i--) {
if (c[i] == '+' || c[i] == '-') {
//这个+-做根节点
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->lChild = node->rChild = NULL; //左右子置空
node->val = c[i]; //将操作符赋值给该节点
node->lChild = BuildTree(c, s, i - 1); //分开的左子树,s到i-1是+-号左边的那部分
node->rChild = BuildTree(c, i + 1, e); //分开的右子树,i+1到e是+-号右边的内容
return node; //返回到上一级给左右子,或者给根
}
}
for (int j = s; j <= e; j++) {
if (c[j] == '*') {
//没有+-后运算符*作根
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->lChild = node->rChild = NULL;
node->val = c[j];
node->lChild = BuildTree(c, s, j - 1);
node->rChild = BuildTree(c, j + 1, e);
return node;
}
}
for (int j = e; j >= s; j--) {
if (c[j] == '/') {
//没有+-后运算符/作根
//因为优先级问题从后面读起
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->lChild = node->rChild = NULL;
node->val = c[j];
node->lChild = BuildTree(c, s, j - 1);
node->rChild = BuildTree(c, j + 1, e);
return node;
}
}
}
```
阅读全文