您的位置:首页 > 其它

LeetCode: Binary Tree Zigzag Level Order Traversal

2013-03-19 11:34 204 查看
出错了一次,改了一次,小失误没用弄好zigzag的排序。题目还是简单的

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void dfs(vector<vector<int>> &ret, stack<TreeNode*> &S, int num) {
stack<TreeNode*> T;
vector<int> level;
while (!S.empty()) {
TreeNode *tmp = S.top();
level.push_back(tmp->val);
if (num%2) {
if (tmp->left) T.push(tmp->left);
if (tmp->right) T.push(tmp->right);
}
else {
if (tmp->right) T.push(tmp->right);
if (tmp->left) T.push(tmp->left);
}
S.pop();
}
ret.push_back(level);
if (!T.empty()) {
S = T;
dfs(ret, S, num+1);
}
}
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int>> ret;
if (!root) return ret;
stack<TreeNode*> S;
S.push(root);
dfs(ret, S, 1);
return ret;
}
};


C#:

/**
* Definition for a binary tree node.
* public class TreeNode {
*     public int val;
*     public TreeNode left;
*     public TreeNode right;
*     public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<int>> ZigzagLevelOrder(TreeNode root) {
Stack<TreeNode> left = new Stack<TreeNode>();
Stack<TreeNode> right = new Stack<TreeNode>();
List<List<int>> ans = new List<List<int>>();
if (root == null) return ans;
left.Push(root);
while (left.Count != 0 || right.Count != 0)
{
List<int> tmp = new List<int>();
if (left.Count != 0) {
while (left.Count != 0) {
TreeNode p = left.Peek();
left.Pop();
tmp.Add(p.val);
if (p.left != null) right.Push(p.left);
if (p.right != null) right.Push(p.right);
}
}
else {
while (right.Count != 0) {
TreeNode p = right.Peek();
right.Pop();
tmp.Add(p.val);
if (p.right != null) left.Push(p.right);
if (p.left != null) left.Push(p.left);
}
}
ans.Add(tmp);
}
return ans;
}
}


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