标签:
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