Topic description
Please implement a function to print the binary tree in a zigzag pattern, that is, the first line is printed in left-to-right order, the second layer is printed in right-to-left order, the third line is printed in left-to-right order, and the other lines are printed in order from left to right. And so on.
Problem solving ideas
Consider using two stacks to record the nodes of each layer: s1 records the odd-numbered layer nodes, and s2 records the even-numbered layer nodes. First push the root node into s1, set the bool variable isOdd to record whether the record is an odd layer and set it to true, and then start traversing the binary tree:
- If the layer is an odd-numbered layer, take out the top node of the s1 stack, add it to the vector, and add its left child node and right child node to the stack s2 in turn, so that the order of printing from the top of the s2 stack of the even-numbered layers is from right to left. If all the nodes in s1 have been taken out, it means that the odd-numbered layers have been printed, so the vector is added to the solution set, the vector is emptied, and isOdd is set to false.
- If the layer is an even layer, take out the top node of the s2 stack, add it to the vector, and add its right child node and left child node to the stack s1 in turn, so that the order of printing from the top of the s1 stack for the odd layer is from left to right. If all the nodes in s2 have been taken out, it means that the even-numbered layers have been printed, so the vector is added to the solution set, the vector is cleared, and isOdd is set to true.
Finally, if both stacks are empty, the binary tree has been printed, and the collection of vectors is returned.
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 stack<TreeNode*> s1,s2; 17 s1.push(pRoot); 18 bool isOdd= true ; 19 vector< int > v; 20 while (s1.size()|| s2.size()){ 21 // The odd-numbered layers add the left child node and the right child node to the stack in turn s2 22 if (isOdd){ 23 TreeNode* node= s1.top(); 24 s1.pop(); 25 v.push_back(node-> val); 26 if (node-> left) 27 s2.push(node-> left); 28 if (node-> right) 29 s2.push(node-> right); 30 if (s1.empty()){ 31 isOdd= false ; 32 vs.push_back(v ); 33 v.clear(); 34 } 35 } 36 // Add the right child node and left child node to the stack s1 37 else { 38 TreeNode* node= s2.top(); 39 s2.pop(); 40 v.push_back(node->val); 41 if(node->right) 42 s1.push(node->right); 43 if(node->left) 44 s1.push(node->left); 45 if(s2.empty()){ 46 isOdd=true; 47 vs.push_back(v); 48 v.clear(); 49 } 50 } 51 } 52 } 53 return vs; 54 } 55 56 };