标签:style blog color io ar 数据 div log sp
一、二叉树
1、定义
二叉树是一棵树,其中每个节点都不能多于2个儿子。
2、实现
typedef struct TreeNode *PtrToNode; typedef PtrToNode Tree; typedef char ElementType; struct TreeNode { ElementType Element; Tree Left; Tree Right; };
3、通过后序表达式构造一个表达式树
void bianli(Tree t) { if (t) { bianli(t->Left); cout << t->Element << " "; bianli(t->Right); } } int main() { char c; stack<Tree> treeStack; while (1) { cout << "Please enter a suffix expression!(the last must is ‘;‘)" << endl; cin >> c; if (c == ‘;‘) { break; } else { if (c == ‘+‘ || c == ‘-‘ || c == ‘*‘ || c == ‘/‘) { auto t2 = treeStack.top(); treeStack.pop(); auto t1 = treeStack.top(); treeStack.pop(); PtrToNode temp2 = new(struct TreeNode); temp2->Element = c; temp2->Left = t1; temp2->Right = t2; treeStack.push(temp2); } else { PtrToNode temp; temp = new(struct TreeNode); temp->Element = c; temp->Left = temp->Right = nullptr; treeStack.push(temp); } } } auto t = treeStack.top(); bianli(t); return 0; }
标签:style blog color io ar 数据 div log sp
原文地址:http://www.cnblogs.com/BlueMountain-HaggenDazs/p/3949048.html