参考浙大陈越姥姥数据结构
#include#include #include #include #include using namespace std; typedef struct t_node* BT; struct t_node{ int val; BT left; BT right; }; BT insert_tree(int val) { BT node = new t_node; node->val = val; node->left = NULL; node->right = NULL; return node; } BT init_tree() { BT root = insert_tree(1); root->left = insert_tree(2); root->right = insert_tree(3); root->left->left = insert_tree(4); root->left->right = insert_tree(5); root->right->left = insert_tree(6); root->right->right = insert_tree(7); return root; } void preOrder(BT root) { // 递归遍历 if(root) { preOrder(root->left); preOrder(root->right); cout << root->val << ' '; } } void preorder(BT root) { stack sta; while(root || !sta.empty()) { while(root) { sta.push(root); // cout << root->val << ' '; // 非递归先序 root = root->left; } if(!sta.empty()) { root = sta.top(); cout << root->val << ' '; // 非递归中序 sta.pop(); root = root->right; } } } void postorder(BT root) { // 非递归后续 stack sta; BT cur = root; BT last = NULL; while(cur) { sta.push(cur); cur=cur->left; } while(!sta.empty()) { cur = sta.top(); sta.pop(); if(cur->right==last || cur->right==NULL) { cout << cur->val << ' '; last = cur; } else { sta.push(cur); cur = cur->right; while(cur) { sta.push(cur); cur = cur->left; } } } } vector > levelorder(BT root) { queue que; que.push(root); vector > ans; while(!que.empty()) { int n = que.size(); vector tmp; for(int i=0; i root = que.front(); tmp.push_back(root->val); que.pop(); // cout << root->val << ' '; if(root->left) que.push(root->left); if(root->right) que.push(root->right); } ans.push_back(tmp); } return ans; } int main() { BT root = init_tree(); // preOrder(root); // cout << endl; // preorder(root); // postorder(root); auto ans = levelorder(root); for(int i=0; i for(int j=0; j



