The "Sword refers to offer" prints a binary tree in the alphabetic order. The sword refers to offer rebuilding a binary tree.
[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]
Question link: http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0? Rp = 3 & ru =/ta/coding-interviews & qru =/ta/coding-interviews/question-ranking
Description
Please implement a function to print a binary tree in the font, that is, the first line is printed from left to right, and the second layer is printed from right to left, the third row is printed from left to right, and the other rows are printed accordingly.
Ideas
It is the same as printing a binary tree into multiple rows. Here we only need to add a number to calculate the number of rows.
/*struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { }};*/class Solution{public:vector<vector<int> > Print(TreeNode* pRoot){vector<vector<int> > ans;vector<int> path;if(pRoot==nullptr)return ans;int cnt = 0;queue<TreeNode*> Q,tmp;Q.push(pRoot);while(!Q.empty()){while(!Q.empty()){TreeNode *pNode = Q.front();path.push_back(pNode->val);Q.pop();if(pNode->left)tmp.push(pNode->left);if(pNode->right)tmp.push(pNode->right);}if(cnt%2)reverse(path.begin(),path.end());cnt++;ans.push_back(path);path.clear();while(!tmp.empty()){Q.push(tmp.front());tmp.pop();}}return ans;}};
Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source