参考:https://blog.csdn.net/hansionz/article/details/81947834
二叉树的基础操作总结
https://blog.csdn.net/hansionz/article/details/81908134
队列的基础操作总结
https://blog.csdn.net/hansionz/article/details/81636644
层次遍历
层次遍历,就是从上到下一层一层的遍历
例如:
思路:
#include <queue> #include <iostream> using namespace std; struct Treenode { int val; Treenode *left; Treenode *right; }; typedef Treenode * binTree; void levelTraverse(binTree root) { queue<binTree> q; q.push(root); if (root == NULL) return ; while (!q.empty()) { int n = q.size(); for (int i = 0;i<n;i++) { binTree cur = q.front(); q.pop(); cout<<cur->val<<endl; if (cur->left != NULL) q.push(cur->left); if (cur->right != NULL) q.push(cur->right); } } } void insertNode(binTree *root, int val) { binTree node = (binTree)malloc(sizeof(Treenode)); node->val = val; node->left= NULL; node->right=NULL; if (*root == NULL) { *root = node; } else { if (val < (*root)->val) insertNode(&(*root)->left, val); else insertNode(&(*root)->right, val); } } int _tmain(int argc, _TCHAR* argv[]) { int nodes[] = {3,9,20,15,7}; int len = 5; binTree root = NULL; for (int i = 0;i<len;i++) { insertNode(&root, nodes[i]); } levelTraverse(root); getchar(); return 0; }