二叉树遍历 (前序 层次 == 深度 广度) 层次遍历
#include<iostream> #include<cstdlib> #include<queue> #include<stack> using namespace std; struct Node; //二叉树节点 class Node{ public: Node(int node):parent(NULL),left(NULL),right(NULL),data(node){} //private: int data; Node* parent; Node* left; Node* right; }; //二叉树 struct binaryTree{ Node* root; binaryTree():root(NULL){} void insert(int a); }; //二叉树插入 void binaryTree::insert(int a) { Node* temp = new Node(a); if(NULL == root) { root = temp; temp->parent = root; return; } Node *y, *tempRoot = root; while(NULL != tempRoot) { y = tempRoot; if(tempRoot->data < a) tempRoot = tempRoot->right; else tempRoot = tempRoot->left; } if(y->data < a) y->right = temp; else y->left = temp; temp->parent = y; } //前序遍历 void preOrder(Node *root) { Node* temp = root; if(temp) cout << temp->data << endl; if(temp->left) preOrder(temp->left); if(temp->right) preOrder(temp->right); } //中序遍历 void inorder(Node* root) { Node* temp = root; if(temp->left) inorder(temp->left); cout << temp->data << endl; if(temp->right) inorder(temp->right); } //层次遍历 void layerOrder(Node *root) { //Node *temp = root; queue<Node*> qu; if(root) qu.push(root); else return; while(!qu.empty()) { Node* temp = qu.front(); if(temp->left) qu.push(temp->left); if(temp->right) qu.push(temp->right); cout << temp->data << endl; qu.pop(); } } //深度优先遍历 void DPF(Node *root) { stack<Node*> st; if(root) st.push(root); else return; while(!st.empty()) { Node *temp = st.top(); st.pop(); if(temp->right) st.push(temp->right); if(temp->left) st.push(temp->left); cout << temp->data << endl; } } //广度优先遍历 void BDF(Node *root) { } int main() { int n = 10; binaryTree bTree; while(--n) { int t = rand()%100; cout << t << endl; bTree.insert(t); } cout << endl; cout << "开始: " <<endl; inorder(bTree.root); cout << "-----------------" << endl; layerOrder(bTree.root); cout << "++++++++++++++++++++" << endl; cout << "前序遍历:" << endl; preOrder(bTree.root); cout << "*********************" << endl; cout << "深度优先遍历: " << endl; DPF(bTree.root); return 0; }