码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Binary Tree Zigzag Level Order Traversal

时间:2015-06-03 00:49:58      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:

To be honest, this problem is designed to let you use stacks. However, I don‘t. In fact, you only need to keep a  flag and switch it between  false and true (initialize to false ). When it is  true , reverse the current level before adding it to the result.

Again, BFS and DFS solutions are provided.

BFS:

 1     vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
 2         vector<vector<int> > levels;
 3         if (!root) return levels;
 4         queue<TreeNode*> toVisit;
 5         toVisit.push(root);
 6         int curLevelNodes = 1;
 7         bool flag = false;
 8         while (!toVisit.empty()) {
 9             vector<int> level;
10             for (int i = 0; i < curLevelNodes; i++) {
11                 TreeNode* node = toVisit.front();
12                 toVisit.pop();
13                 level.push_back(node -> val);
14                 if (node -> left) toVisit.push(node -> left);
15                 if (node -> right) toVisit.push(node -> right);
16             }
17             if (flag) {
18                 reverse(level.begin(), level.end());
19                 flag = false;
20             }
21             else flag = true;
22             levels.push_back(level);
23             curLevelNodes = toVisit.size();
24         }
25         return levels;
26     }

DFS:

 1 void dfs(TreeNode* node, int curLevel, bool& nextLevel, vector<int>& level) {
 2         if (!node) return;
 3         if (curLevel == 1) {
 4             level.push_back(node -> val);
 5             if (node -> left || node -> right) nextLevel = true;
 6         }
 7         else {
 8             dfs(node -> left, curLevel - 1, nextLevel, level);
 9             dfs(node -> right, curLevel - 1, nextLevel, level);
10         }
11     }
12     vector<vector<int> > zigzagLevelOrder(TreeNode* root) {
13         vector<vector<int> > levels;
14         if (!root) return levels;
15         int curLevel = 1;
16         bool nextLevel = true, flag = false;
17         while (nextLevel) {
18             nextLevel = false;
19             vector<int> level;
20             dfs(root, curLevel++, nextLevel, level);
21             if (flag) {
22                 reverse(level.begin(), level.end());
23                 flag = false;
24             } 
25             else flag = true;
26             levels.push_back(level);
27         }
28         return levels;
29     }

 

[LeetCode] Binary Tree Zigzag Level Order Traversal

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4548038.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!