タイトル説明
他の行では、印刷の右の順に、左から右、右から左に印刷するために、第2の層の第一の印刷ライン、第三行に左ジグザグプリント機能バイナリツリー、すなわち、に従って実施前後。
思考
- 思考スタックは、2つのスタックは、S1、S2は、偶数行に押し込ま奇数ラインに押し込ま、配置、偶数、奇数ライン場合、スタックS1、S2のポップトップスタックの頂部に押圧されるCOUNTを用いて奇数行の現在の行を計算します右、左と、スタックの最上部に圧入、空S1まで、逆に偶数行場合、S2は、スタックをポップし、左と右の圧力に押し付け。それが空の場合は、カウントを完了した後に++、res_pが空であるか否かを決定する必要を覚えて、それが最後に既にあります
- トラバース配列の考え方によれば、キューを考え、出力層は偶数、正の出力は逆の奇数層である場合
コード
この方法の一つ:
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > res;
vector<int> res_p;
if(pRoot == NULL)
return res;
stack<TreeNode*> S1_tree;
stack<TreeNode*> S2_tree;
S1_tree.push(pRoot);
res_p.push_back(pRoot->val);
res.push_back(res_p);
res_p.clear();
int count = 0;
while(S1_tree.size()>0 || S2_tree.size()>0)
{
if(count%2 == 0)
{
while(S1_tree.size() > 0)
{
TreeNode* current = S1_tree.top();
S1_tree.pop();
if(current->right)
{
S2_tree.push(current->right);
res_p.push_back(current->right->val);
}
if(current->left)
{
S2_tree.push(current->left);
res_p.push_back(current->left->val);
}
}
if(res_p.size()>0)
{
res.push_back(res_p);
res_p.clear();
}
count++;
}
else
{
while(S2_tree.size() > 0)
{
TreeNode* current = S2_tree.top();
S2_tree.pop();
if(current->left)
{
S1_tree.push(current->left);
res_p.push_back(current->left->val);
}
if(current->right)
{
S1_tree.push(current->right);
res_p.push_back(current->right->val);
}
}
if(res_p.size()>0)
{
res.push_back(res_p);
res_p.clear();
}
count++;
}
}
return res;
}
};
方法2:
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > res;
vector<int> res_p;
if(pRoot == NULL)
return res;
queue<TreeNode*> q_Tree;
q_Tree.push(pRoot);
res_p.push_back(pRoot->val);
res.push_back(res_p);
res_p.clear();
int count = 1;
while(q_Tree.size()>0)
{
int number = q_Tree.size();
while(number > 0)
{
TreeNode* current = q_Tree.front();
q_Tree.pop();
if(current->left)
{
q_Tree.push(current->left);
res_p.push_back(current->left->val);
}
if(current->right)
{
q_Tree.push(current->right);
res_p.push_back(current->right->val);
}
number--;
}
if(count%2 == 0 && res_p.size()>0)
{
res.push_back(res_p);
res_p.clear();
}
else if(count%2 == 1 && res_p.size()>0)
{
reverse(res_p.begin(),res_p.end());
res.push_back(res_p);
res_p.clear();
}
count++;
}
return res;
}
};