题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
解题思路:本题通过分析,需要采用双端队列对中间节点的信息进行存储。
1)将根节点存入队列中
2)定义间接树的信息pRoot,表示当前遍历的结点信息
3)弹出队列头的结点,然后分别看pRoot的左右孩子是否为空,若不为空则,插入队列尾部
4)循环上述2) 3)操作直至队列为空
1 #include <iostream> 2 #include <vector> 3 #include <deque> 4 #include <malloc.h> 5 using namespace std; 6 struct TreeNode { 7 int val; 8 struct TreeNode *left; 9 struct TreeNode *right; 10 TreeNode(int x) : 11 val(x), left(NULL), right(NULL) { 12 } 13 }; 14 class Solution { 15 public: 16 //借助辅助的双端队列进行间接存储 17 vector<int> PrintFromTopToBottom(TreeNode* root) { 18 vector<int> result; 19 if(root == NULL) 20 return result; 21 deque<TreeNode *> dequeTree; 22 dequeTree.push_back(root); 23 while(!dequeTree.empty()) 24 { 25 TreeNode *pRoot = dequeTree.front(); 26 result.push_back(pRoot->val); 27 dequeTree.pop_front(); 28 if(pRoot->left) 29 { 30 dequeTree.push_back(pRoot->left); 31 } 32 if(pRoot->right) 33 { 34 dequeTree.push_back(pRoot->right); 35 } 36 } 37 } 38 }; 39 //先序建立二叉树 40 TreeNode *CreateBiTree(){ 41 int ch; 42 43 TreeNode *T; 44 cin>>ch; 45 if(ch== 0)T=NULL; 46 else{ 47 T = (TreeNode *)malloc(sizeof(TreeNode)); 48 T->val = ch; 49 cout<<"输入左子节点"<<endl; 50 T->left = CreateBiTree(); 51 cout<<"输入右子节点"<<endl; 52 T->right = CreateBiTree(); 53 } 54 return T;//返回根节点 55 } 56 //先序遍历二叉树 57 void PreOrderTraverse(TreeNode *T){ 58 if(T) 59 { 60 cout<<T->val<<" "; 61 PreOrderTraverse(T->left); 62 PreOrderTraverse(T->right); 63 } 64 } 65 int main() 66 { 67 TreeNode *T1; 68 cout<<"输入根节点:"<<endl; 69 T1 = CreateBiTree();//建立 70 cout<<"树1的先序遍历为"<<endl; 71 PreOrderTraverse(T1);//输出 72 cout<<endl; 73 cout<<"从上往下打印结果"<<endl; 74 vector<int> v; 75 Solution s; 76 v = s.PrintFromTopToBottom(T1); 77 for(int i=0;i<v.size();i++) 78 { 79 cout<<v[i]<<" "; 80 } 81 return 0; 82 }