[LeetCode] Binary Tree Level Order Traversal II

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


下一篇:[LeetCode] Binary Tree Postorder Traversal