标签:
To be honest, I do not know whether this problem is designed to let you use stacks. Anyway, I don‘t. Here are my codes, both BFS and DFS version.
1 // BFS 2 vector<vector<int>> zigzagLevelOrder(TreeNode* root) { 3 vector<vector<int> > levels; 4 if (!root) return levels; 5 queue<TreeNode*> toVisit; 6 toVisit.push(root); 7 int curLevelNodes = 1; 8 bool flag = false; 9 while (!toVisit.empty()) { 10 vector<int> level; 11 for (int i = 0; i < curLevelNodes; i++) { 12 TreeNode* node = toVisit.front(); 13 toVisit.pop(); 14 level.push_back(node -> val); 15 if (node -> left) toVisit.push(node -> left); 16 if (node -> right) toVisit.push(node -> right); 17 } 18 if (flag) { 19 reverse(level.begin(), level.end()); 20 flag = false; 21 } 22 else flag = true; 23 levels.push_back(level); 24 curLevelNodes = toVisit.size(); 25 } 26 return levels; 27 } 28 29 // DFS 30 void dfs(TreeNode* node, int curLevel, bool& nextLevel, vector<int>& level) { 31 if (!node) return; 32 if (curLevel == 1) { 33 level.push_back(node -> val); 34 if (node -> left || node -> right) nextLevel = true; 35 } 36 else { 37 dfs(node -> left, curLevel - 1, nextLevel, level); 38 dfs(node -> right, curLevel - 1, nextLevel, level); 39 } 40 } 41 vector<vector<int> > zigzagLevelOrder(TreeNode* root) { 42 vector<vector<int> > levels; 43 if (!root) return levels; 44 int curLevel = 1; 45 bool nextLevel = true, flag = false; 46 while (nextLevel) { 47 nextLevel = false; 48 vector<int> level; 49 dfs(root, curLevel++, nextLevel, level); 50 if (flag) { 51 reverse(level.begin(), level.end()); 52 flag = false; 53 } 54 else flag = true; 55 levels.push_back(level); 56 } 57 return levels; 58 }
Update
Thanks to the remind of ljdsoft1, I have rewritten the code to traverse the nodes in ziazag-order instead of simply reversing it. The code is as follows, using two stacks.
1 class Solution { 2 public: 3 vector<vector<int>> zigzagLevelOrder(TreeNode* root) { 4 vector<vector<int> > levels; 5 if (!root) return levels; 6 stack<TreeNode*> curLevel, nextLevel; 7 curLevel.push(root); 8 bool reversed = false; 9 while (!curLevel.empty()) { 10 vector<int> level; 11 while (!curLevel.empty()) { 12 TreeNode* node = curLevel.top(); 13 curLevel.pop(); 14 level.push_back(node -> val); 15 if (reversed) { 16 if (node -> right) nextLevel.push(node -> right); 17 if (node -> left) nextLevel.push(node -> left); 18 } 19 else { 20 if (node -> left) nextLevel.push(node -> left); 21 if (node -> right) nextLevel.push(node -> right); 22 } 23 } 24 levels.push_back(level); 25 swap(curLevel, nextLevel); 26 reversed = !reversed; 27 } 28 return levels; 29 } 30 };
[LeetCode] Binary Tree Zigzag Level Order Traversal
标签:
原文地址:http://www.cnblogs.com/jcliBlogger/p/4620339.html