剑指Offer21 二叉树的层序遍历
1 /************************************************************************* 2 > File Name: 21_PrintTreeTopToBottom.cpp 3 > Author: Juntaran 4 > Mail: JuntaranMail@gmail.com 5 > Created Time: 2016年08月30日 星期二 20时24分53秒 6 ************************************************************************/ 7 8 #include <stdio.h> 9 #include <stdlib.h> 10 #include <malloc.h> 11 #include <bits/stdc++.h> 12 13 using namespace std; 14 15 // 二叉树结构体 16 struct TreeNode 17 { 18 int val; 19 TreeNode* left; 20 TreeNode* right; 21 }; 22 23 // 层序遍历 24 void PrintTreeTopToBottom(TreeNode* root) 25 { 26 if (root == NULL) 27 return; 28 29 vector<TreeNode*> vec; 30 vec.push_back(root); 31 32 int cur = 0; 33 while (cur < vec.size()) 34 { 35 printf("%d ", vec[cur]->val); 36 if (vec[cur]->left) 37 vec.push_back(vec[cur]->left); 38 if (vec[cur]->right) 39 vec.push_back(vec[cur]->right); 40 ++cur; 41 } 42 printf("\n"); 43 } 44 45 TreeNode* createTree() 46 { 47 TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode)); 48 root->val = 8; 49 root->left = (TreeNode*)malloc(sizeof(TreeNode)); 50 root->left->val = 8; 51 root->right = (TreeNode*)malloc(sizeof(TreeNode)); 52 root->right->val = 7; 53 root->right->left = NULL; 54 root->right->right = NULL; 55 root->left->left = (TreeNode*)malloc(sizeof(TreeNode)); 56 root->left->left->val = 9; 57 root->left->left->left = NULL; 58 root->left->left->right = NULL; 59 root->left->right = (TreeNode*)malloc(sizeof(TreeNode)); 60 root->left->right->val = 2; 61 root->left->right->left = (TreeNode*)malloc(sizeof(TreeNode)); 62 root->left->right->left->val = 4; 63 root->left->right->left->left = NULL; 64 root->left->right->left->right = NULL; 65 root->left->right->right = (TreeNode*)malloc(sizeof(TreeNode)); 66 root->left->right->right->val = 7; 67 root->left->right->right->left = NULL; 68 root->left->right->right->right = NULL; 69 70 return root; 71 } 72 73 int main() 74 { 75 TreeNode* test = createTree(); 76 PrintTreeTopToBottom(test); 77 }