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

[LeetCode] Binary Tree Level Order Traversal II

时间:2015-06-03 00:44:08      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:

Well, I do not see what this problem is for. The same code of Binary Tree Level Order Traversal can be used here. The only difference is that we should reverse the result before we return. 

Again, both BFS and DFS solutions.

BFS:

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

DFS:

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

 

[LeetCode] Binary Tree Level Order Traversal II

标签:

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

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