The sword refers to the offer-print the binary tree into multiple lines

 

Topic description

 
Print the binary tree layer by layer from top to bottom, and the nodes in the same layer are output from left to right. Each layer outputs one line.
 

Problem solving ideas

 

Or use the idea of ​​layer-order traversal, set a queue to initially push the root node, and print out the node value each time the node at the top of the queue is deleted. If it has left and right child nodes, then push the left and right child nodes into the queue in turn, so Iterate until the queue is empty.

Since this question requires line-by-line output, two variables need to be set to keep the lines: needPrint records the number of nodes that still need to be printed in the current line, and nextLevel records the number of nodes that need to be printed in the next line. Each time a node is printed, the number of nodes remaining in the current line, needPrint, is decremented by 1; each time a child node is put into the queue, the number of nodes in the next line, nextLevel, is increased by 1. After printing the nodes, if needPrint is 0, it means that all nodes in the current line have been printed, so set needPrint to nextLevel, the number of nodes in the next line, and set nextLevel to 0.

 

code

 

 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> > vs;
15             if(pRoot){
16                 vector<int> v;
17                 queue<TreeNode*> q;
18                 q.push(pRoot);
19                 int needPrint=1;
20                 int nextLevel=0;
21                 while(q.size()){
22                     TreeNode* node=q.front();
23                     v.push_back(node->val);
24                     needPrint--;
25                     q.pop();
26                     if(node->left){
27                         q.push(node->left);
28                         nextLevel++;
29                     }
30                     if(node->right){
31                         q.push(node->right);
32                         nextLevel++;
33                     }
34                     if(needPrint==0){
35                         vs.push_back(v);
36                         v.clear();
37                         needPrint=nextLevel;
38                         nextLevel=0;
39                     }
40                 }
41             }
42             return vs;
43         }
44     
45 };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324689417&siteId=291194637