把二叉树打印成多行

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

C++:

 1 /*
 2 struct TreeNode {
 3     int val;
 4     struct TreeNode *left;
 5     struct TreeNode *right;
 6     TreeNode(int x) :
 7             val(x), left(NULL), right(NULL) {
 8     }
 9 };
10 */
11 class Solution {
12 public:
13         vector<vector<int> > Print(TreeNode* pRoot) {
14             vector<vector<int> > res ;
15             if (pRoot == NULL)
16                 return res ;
17             queue<TreeNode*> q ;
18             q.push(pRoot) ;
19             while(!q.empty()){
20                 vector<int> list ;
21                 int len = q.size() ;
22                 for(int i = 0 ; i < len ; i++){
23                     TreeNode* node = q.front() ;
24                     q.pop() ;
25                     list.push_back(node->val) ;
26                     if (node->left != NULL)
27                         q.push(node->left) ;
28                     if (node->right != NULL)
29                         q.push(node->right) ;
30                 }
31                 if (list.size() != 0)
32                    res.push_back(list) ;
33             }
34             return res ;
35         }
36     
37 };
原文地址:https://www.cnblogs.com/mengchunchen/p/10620006.html