题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
和从上往下打印二叉树类似 ----> 传送门
两个栈来回倒
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> ret;
if (nullptr == pRoot) {
return ret;
}
stack<TreeNode *> global;
global.push(pRoot);
bool isEnd = false;
while (false == isEnd) {
isEnd = true;
stack<TreeNode *> local;
vector<int> vt;
while (!global.empty()) {
TreeNode *temp = global.top();
global.pop();
if (nullptr != temp) {
vt.push_back(temp->val);
local.push(temp->left);
local.push(temp->right);
if ((nullptr != temp->left) || (nullptr != temp->right)) {
isEnd = false;
}
}
else {
local.push(nullptr);
local.push(nullptr);
}
}
ret.push_back(vt);
while(local.size()) {
global.push(local.top());
local.pop();
}
}
return ret;
}
};
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>> ret;
if (nullptr == pRoot) {
return ret;
}
queue<TreeNode *> myQueue;
myQueue.push(pRoot);
while(myQueue.size()) {
int size = myQueue.size();
vector<int> vt;
while(size--) {
TreeNode *temp = myQueue.front();
myQueue.pop();
vt.push_back(temp->val);
if (nullptr != temp->left)
myQueue.push(temp->left);
if (nullptr != temp->right)
myQueue.push(temp->right);
}
ret.push_back(vt);
}
return ret;
}
};