#include<iostream>
#include<queue>
#include<stack>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
//TreeNode(int val) :val(val) {};
};
void printVector(vector<int> &v1)
{
for (int i = 0; i < v1.size(); i++) {
cout << v1[i] << " ";
}
cout << endl;
}
class Solution
{
public:
vector<int> pre;
vector<int> in;
vector<int> post;
vector<int> floor;
vector<int> zfloor;
//前序遍历
void preorder(TreeNode* root) {
if (root != nullptr) {
pre.push_back(root->val); //print root
preorder(root->left); //print left tree
preorder(root->right); //print right tree
}
}
//中序遍历
void inorder(TreeNode* root) {
if (root != nullptr) {
inorder(root->left); //print left tree
in.push_back(root->val); //print root
inorder(root->right); //print right tree
}
}
//后序遍历
void postorder(TreeNode* root) {
if (root != nullptr) {
postorder(root->left); //print left tree
postorder(root->right); //print right tree
post.push_back(root->val); //print root
}
}
//层序遍历
void floorPrint(TreeNode* root){
queue<TreeNode*> q;
if (root != nullptr) { //queue : root root->left root->right
//queue : root(pop) root->left root->right root->left->left root->left->right
q.push(root); //queue : root(out) root->left(out) root->right root->left->left root->left->right root->right->left root->right->right
}
while (!q.empty()) {
floor.push_back(q.front()->val);
if (q.front()->left != nullptr) {
q.push(q.front()->left);
}
if (q.front()->right != nullptr) {
q.push(q.front()->right);
}
q.pop();
}
}
//z字形层序遍历
void zfloorPrint(TreeNode* root) {
stack<TreeNode*> s1;
stack<TreeNode*> s2;
int i = 1;
if (root != nullptr) {
s1.push(root);
}
while (s1.empty() == false || s2.empty() == false) {
if (i % 2) {
while (!s1.empty()) {
zfloor.push_back(s1.top()->val);
if (s1.top()->right != nullptr) s2.push(s1.top()->right);
if (s1.top()->left != nullptr) s2.push(s1.top()->left);
s1.pop();
}
}
else {
while (!s2.empty()) {
zfloor.push_back(s2.top()->val);
if (s2.top()->left != nullptr) s1.push(s2.top()->left);
if (s2.top()->right != nullptr) s1.push(s2.top()->right);
s2.pop();
}
}
i++;
}
}
//二叉树创建
TreeNode* buildTree(int arr[],int len,int i)
{
if (len < 1) return NULL;
TreeNode* root = NULL;
if (i < len && arr[i] != '#') {
root = new TreeNode();
if (root == NULL)return NULL;
root->val = arr[i];
root->left = buildTree(arr, len, 2 * i + 1);
root->right = buildTree(arr, len, 2 * i + 2);
}
return root;
}
};
int main()
{
Solution s;
int arr[] = { 1, 2, 3, 4, 5, '#', 6, '#', '#', 7, 8 };
TreeNode* head;
//生成二叉树
head = s.buildTree(arr, sizeof(arr) / sizeof(arr[0]), 0);
//前序遍历
s.preorder(head);
printVector(s.pre);
//中序遍历
s.inorder(head);
printVector(s.in);
//后序遍历
s.postorder(head);
printVector(s.post);
//层序遍历
s.floorPrint(head);
printVector(s.floor);
//z层序遍历
s.zfloorPrint(head);
printVector(s.zfloor);
return 0;
}
Z字层序遍历用了两个栈和一个计数器i用来计算层次。
最开始将根结点压入栈1,此时栈2为空。
i是奇数时,将栈1中的结点出栈,出栈前检查该结点的左右孩子,如果都存在就压入栈2,先右后左。直至栈1为空。
i是偶数时,将栈2的结点依次出栈,出栈前检查该结点的左右孩子,如果都存在就压入栈1,先左后右。直至栈2为空。
循环,直至栈1栈2均为空。每循环一次计数器i+1;