I. Binary Tree
1. Definition
A binary tree is a tree. Each node cannot have more than two sons.
2. Implementation
typedef struct TreeNode *PtrToNode;typedef PtrToNode Tree;typedef char ElementType;struct TreeNode{ ElementType Element; Tree Left; Tree Right;};
3. Construct an expression tree using a forward expression
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;}
Data Structure and Algorithm Analysis Study Notes (4) -- tree ADT