如果用数组形式建树进行的话很简单,表面上就不需要用到栈的知识,也比较容易想到,用结构体建树的方法就要不断push,pop啊然后感觉一下想不出什么时候push,pop,或者push pop 什么,给个样例:数组建树是这样的开始说明a[i]的左儿子a[2*i+1] 右儿子a[2*i+2]
A(B(D),C)
用数组构建树的算法就是:创一个数组 char a[100],取一个中间值叫做current_index吧初始值为0; 然后不断读取这个字符串,一个一个读,遇到字母,a[current_index]等于当前字符, 遇到左括号current_index=current_index*2+1, 遇到逗号current_index=current_index+1
遇到右括号 判断current_index奇偶 如果current_index是奇数就—1再除以二,如果偶数就—2再除以二
然后如果用结构体建树的话就要用到栈了,其实用数组原理上也用到栈了但可以让人感觉不出来
摘自计算课上的代码 帮你们变成彩色了容易看 滑稽 按照代码人工跑一遍就能懂他的意思了,但是感觉我还是想不出来
Node *build(char *s,int len)
{
stack<Node*>sta;
const int left = 1,right = 2;
int flag = 0;
Node *rootnode = NULL;
Node *currnode = NULL;
int index = 0;
char c = s[index];
while (index < len) {
switch (c){
case '(':
flag = left;
sta.push(currnode);
break;
case ',':
flag = right;
break;
case ')':
sta.pop();
break;
default:
currnode = init(c);
if (rootnode == NULL)
rootnode = currnode;
else if (flag == left) {
sta.top()->lchild = currnode;
}
else if (flag == right) {
sta.top()->rchild = currnode;
}
break;
}
//rootnode = init(c);
c = s[++index];
}
return rootnode;
}
栈的目的就是不断记录每一层的跟节点,这是关键,感觉知道这个就可以了