从上往下打印二叉树
从上往下打印二叉树
题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
两种方法, 一栈, 一种队列
栈: 利用两个栈, 第global保存每一层父节点, local保存每一层的子节点, 先左后右的顺序压栈, 当global栈空时, 把local栈中元素压入global中并清空local栈,
注意: global中元素为NULL时, local栈压入NULL
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
vector<int> ret;
stack<TreeNode *> global;
global.push(root);
bool isEnd = false;
if (NULL == root) {
return ret;
}
while(false == isEnd) {
isEnd = true;
stack<TreeNode *> local;
while(global.size() != 0) {
TreeNode *temp = global.top();
global.pop();
if (NULL != temp) {
ret.push_back(temp->val);
local.push(temp->left);
local.push(temp->right);
if ((NULL != temp->left) || (NULL != temp->right)) {
isEnd = false;
}
}
else {
local.push(NULL);
local.push(NULL);
}
}
while(local.size() != 0) {
global.push(local.top());
local.pop();
}
}
return ret;
}
};
队列版本: 与栈版本没太大区别, 把上一层元素放入队尾, 然后把上一层的节点对应的子节点依次放入队尾
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
vector<int> ret;
queue<TreeNode *> myQueue;
if (NULL == root) {
return ret;
}
myQueue.push(root);
while(!myQueue.empty()) {
TreeNode *temp = myQueue.front();
myQueue.pop();
ret.push_back(temp->val);
if (NULL != temp->left) {
myQueue.push(temp->left);
}
if (NULL != temp->right)
myQueue.push(temp->right);
}
return ret;
}
};
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/