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

[LeetCode] Binary Tree Level Order Traversal

时间:2015-06-03 00:36:39      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

A classic tree traversal problem. I share my two solutions here: BFS and DFS.

BFS:

 1     vector<vector<int>> levelOrder(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             levels.push_back(level);
17             numLevelNodes = toVisit.size();
18         }
19         return levels;
20     }

DFS:

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

 

[LeetCode] Binary Tree Level Order Traversal

标签:

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

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