题目

    3
/ \
9  20
/  \
15   7


[
[3],
[20,9],
[15,7]
]

1.stack 双栈

2.tree

3.vector

代码

newcoder

/*
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<int> subret;
vector<vector<int>> ret;

//1.入口检查
if(!pRoot)
return ret;

int cur = 1;
int next = 0 ;

//level[0]奇数级节点的栈，从左至右存储,level[1]偶数级节点的栈，从右至左存储,
stack<TreeNode*> level[2];
//level[0]:stack1,level[1]:stack2

//将根节点放入stack2中
level[1].push(pRoot);

while(!level[0].empty()||!level[1].empty())
{
while(!level[cur].empty())
{
TreeNode* curNode=level[cur].top();
subret.push_back(curNode->val);
level[cur].pop();
if(cur==0)//
{
if(curNode->right)
level[next].push(curNode->right);

if(curNode->left)
level[next].push(curNode->left);
}
else
{
if(curNode->left)
level[next].push(curNode->left);

if(curNode->right)
level[next].push(curNode->right);

}
}
if(level[cur].empty())
{
cur=1-cur;
next=1-next;
ret.push_back(subret);
subret.clear();
}
}

return ret;
}

};

leetcode

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
//局部变量
std::stack<TreeNode*> stack1;
std::stack<TreeNode*> stack2;
vector<vector<int>> ret;
vector<int> temp;

//鲁棒性检查
if(!root)
return ret;

//栈1中放入根节点
stack1.push(root);

//如果两个栈中还有节点
while(!stack1.empty()||!stack2.empty())
{
//栈2是空的就打印栈1
if(stack2.empty())
{
while(!stack1.empty())
{
///记录当前node,temp，pop
TreeNode* cur=stack1.top();
temp.push_back(cur->val);
stack1.pop();
//注意左右顺序
if(cur->left)
stack2.push(cur->left);
if(cur->right)
stack2.push(cur->right);
}
//栈1打印完，push temp容器，清空temp，
//开始打印栈2，操作和上面一样，只是左右顺序不同
ret.push_back(temp);
temp.clear();
}
else
{
if(stack1.empty())
{
while(!stack2.empty())
{
TreeNode* cur=stack2.top();
temp.push_back(cur->val);
stack2.pop();
if(cur->right)
stack1.push(cur->right);
if(cur->left)
stack1.push(cur->left);
}
ret.push_back(temp);
temp.clear();
}
}
}

return ret;
}
};

问题

1.vector

2.双栈和二叉树有对称的情况，所以第二种解法更好。

posted @ 2019-02-09 10:18  lightmare  阅读(91)  评论(0编辑  收藏