"Sword refers to offer" prints a binary tree into multiple rows, and "Sword refers to offer" multiple rows
[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/445c44d982d04483b04a54f298796288? Rp = 3 & ru =/ta/coding-interviews & qru =/ta/coding-interviews/question-ranking
Description
Print the binary tree from top to bottom, and output the tree from left to right at the same layer node. Each layer outputs a row.
Ideas
Considering that this is a problem of width-first search, the nodes at the same layer must be in the same row in the array. Therefore, each time we traverse the nodes at the layer, we also need to keep the storage path, this requires two queues.
/*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;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);}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