1.二叉树
class treenode {
public:
int val;
treenode* left;
treenode* right;
treenode(int x):val(x),left(nullptr),right(nullptr){}
}; //定义树;
int main() {
treenode* root = new treenode(10);
root->left = new treenode(9);
root->right = new treenode(8);
root->left->left= new treenode(7);
root->right->right = new treenode(6);
root->left->right = new treenode(5);
root->right->left = new treenode(4);
root->left->left->left = new treenode(3);
}// 创建树;
void pre(treenode* t) {
if (t == nullptr) return;
cout << t->val << " ";
pre(t->left);
pre(t->right);
}// 先序遍历(递归),中后续类似
void prefeidigui(treenode* t) {
if (t == nullptr) return;
stack<treenode*> s;
s.push(t);
while (!s.empty()) {
treenode* temp = s.top();
cout << temp->val << " ";
s.pop();
if (temp->right) s.push(temp->right);
if (temp->left) s.push(temp->left);
}
}// 先序遍历,非递归实现;
void midfeidigui(treenode* t) {
if (t == nullptr) return;
treenode* current = t;
stack<treenode*> s;
while (current || !s.empty()) {
while (current) {
s.push(current);
current = current->left;
}
current = s.top();
cout << current->val << " ";
s.pop();
current = current->right;
}
}//中序遍历非递归实现;
void houfeidigui(treenode* t) {
if (t == nullptr) return;
stack<treenode*> s;
treenode* current = t;
treenode* pre = t;
while (current || !s.empty()) {
while (current) {
s.push(current);
current = current->left;
}
current = s.top();
if (current->right != nullptr && pre != current->right) {
current = current->right;
}
else {
cout << current->val << " ";
pre = current;
current = nullptr;
s.pop();
}
}
}//后序遍历非递归实现
2.链表
class linklist {
public:
int val;
linklist* next;
linklist(int x):val(x),next(nullptr){}
};// 定义链表
void charu(linklist*& t, int val) {
linklist* newnode = new linklist(val);
if (t == nullptr) t = newnode;
else {
linklist* temp = t;
while (temp->next) temp = temp->next;
temp->next = newnode;
}
}// 头插法
int main() {
linklist* t = nullptr;
charu(t, 1);
charu(t, 2);
charu(t, 3);
charu(t, 4);
charu(t, 5);
for (linklist* temp = t; temp != nullptr; temp = temp->next)
cout << temp->val << " ";
cin.get(); //创建链表