107. Binary Tree Level Order Traversal II
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
在102题基础上对输出结果进行反转操作,重新定义了一个vector,将102的结果倒序存入vector中。
代码如下:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<vector<int>> levelOrderBottom(TreeNode* root) { 13 vector<vector<int>> lorder; 14 vector<vector<int>> lforder; 15 if(root == NULL) 16 { 17 return lorder; 18 } 19 queue<TreeNode*> q; 20 q.push(root); 21 vector<int> level_tmp2; 22 while(!q.empty()) 23 { 24 level_tmp2.clear(); 25 queue<TreeNode*> level_tmp1; 26 TreeNode* node = q.front(); 27 int size = q.size(); 28 29 for(int i = 0; i < size; i++) 30 { 31 TreeNode* node = q.front(); 32 q.pop(); 33 if(node->left) 34 { 35 level_tmp1.push(node->left); 36 } 37 if(node->right) 38 { 39 level_tmp1.push(node->right); 40 } 41 level_tmp2.push_back(node->val); 42 } 43 while(!level_tmp1.empty()) 44 { 45 q.push(level_tmp1.front()); 46 level_tmp1.pop(); 47 } 48 lorder.push_back(level_tmp2); 49 } 50 int n = lorder.size(); 51 for(int i = n-1; i >= 0; i--) 52 { 53 lforder.push_back(lorder[i]); 54 }//reverse(lorder.begin(), lorder.end()); 55 return lforder; 56 } 57 };