您的位置:首页 > 职场人生

面试题61:按之字形顺序打印二叉树

2017-04-28 22:52 495 查看
题目描述

请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

解:

两个栈

/*
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>> result;
if(!pRoot)
return result;
stack<TreeNode*> s[2];
int current = 0;
int next = 1;
s[current].push(pRoot);
vector<int> v;
while(!s[current].empty() || ! s[next].empty()){
TreeNode* pCur = s[current].top();
s[current].pop();
v.push_back(pCur->val);
if(current == 0){
if(pCur->left)
s[next].push(pCur->left);
if(pCur->right)
s[next].push(pCur->right);
}else{
if(pCur->right)
s[next].push(pCur->right);
if(pCur->left)
s[next].push(pCur->left);
}

if(s[current].empty()){
result.push_back(v);
v.clear();
current = 1 - current;
next = 1 - next;
}
}
return result;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息