LeetCode: Binary Tree Zigzag Level Order Traversal

出错了一次,改了一次,小失误没用弄好zigzag的排序。题目还是简单的

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     void dfs(vector<vector<int>> &ret, stack<TreeNode*> &S, int num) {
13         stack<TreeNode*> T;
14         vector<int> level;
15         while (!S.empty()) {
16             TreeNode *tmp = S.top();
17             level.push_back(tmp->val);
18             if (num%2) {
19                 if (tmp->left) T.push(tmp->left);
20                 if (tmp->right) T.push(tmp->right);
21             }
22             else {
23                 if (tmp->right) T.push(tmp->right);
24                 if (tmp->left) T.push(tmp->left);
25             }
26             S.pop();
27         }
28         ret.push_back(level);
29         if (!T.empty()) {
30             S = T;
31             dfs(ret, S, num+1);
32         }
33     }
34     vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
35         // Start typing your C/C++ solution below
36         // DO NOT write int main() function
37         vector<vector<int>> ret;
38         if (!root) return ret;
39         stack<TreeNode*> S;
40         S.push(root);
41         dfs(ret, S, 1);
42         return ret;
43     }
44 };

 C#:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left;
 6  *     public TreeNode right;
 7  *     public TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public List<List<int>> ZigzagLevelOrder(TreeNode root) {
12         Stack<TreeNode> left = new Stack<TreeNode>();
13         Stack<TreeNode> right = new Stack<TreeNode>();
14         List<List<int>> ans = new List<List<int>>();
15         if (root == null) return ans;
16         left.Push(root);
17         while (left.Count != 0 || right.Count != 0)
18         {
19             List<int> tmp = new List<int>();
20             if (left.Count != 0) {
21                 while (left.Count != 0) {
22                     TreeNode p = left.Peek();
23                     left.Pop();
24                     tmp.Add(p.val);
25                     if (p.left != null) right.Push(p.left);
26                     if (p.right != null) right.Push(p.right);
27                 }
28             }
29             else {
30                 while (right.Count != 0) {
31                     TreeNode p = right.Peek();
32                     right.Pop();
33                     tmp.Add(p.val);
34                     if (p.right != null) left.Push(p.right);
35                     if (p.left != null) left.Push(p.left);
36                 }
37             }
38             ans.Add(tmp);
39         }
40         return ans;
41     }
42 }
View Code
原文地址:https://www.cnblogs.com/yingzhongwen/p/2968815.html