题目:
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,#,#,15,7}
,
3 / 9 20 / 15 7
return its bottom-up level order traversal as:
[ [15,7] [9,20], [3], ]
解题思路:
广度优先遍历,然后对结果进行翻转。
代码:
1 /** 2 * Definition for binary tree 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> > ans; 14 if (root == NULL) return ans; 15 queue<TreeNode*> one; 16 queue<TreeNode*> another; 17 vector<int> cur_ans; 18 TreeNode* cur_node; 19 20 one.push(root); 21 22 while (!one.empty() || !another.empty()) { 23 if (!one.empty()) { 24 while (!one.empty()) { 25 cur_node = one.front(); 26 one.pop(); 27 cur_ans.push_back(cur_node->val); 28 if (cur_node->left) another.push(cur_node->left); 29 if (cur_node->right) another.push(cur_node->right); 30 } 31 ans.push_back(cur_ans); 32 cur_ans.clear(); 33 } 34 if (!another.empty()) { 35 while (!another.empty()) { 36 cur_node = another.front(); 37 another.pop(); 38 cur_ans.push_back(cur_node->val); 39 if (cur_node->left) one.push(cur_node->left); 40 if (cur_node->right) one.push(cur_node->right); 41 } 42 ans.push_back(cur_ans); 43 cur_ans.clear(); 44 } 45 } 46 reverse(ans.begin(), ans.end()); 47 return ans; 48 } 49 };