题目:
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] ]
分类:Tree BFS
代码:
递归:
1 class Solution { 2 protected: 3 vector<vector<int>> ans; 4 void dfs(TreeNode *root, int height){ 5 if (root == NULL) 6 return; 7 while (ans.size() <= height) 8 ans.push_back(vector<int>()); 9 ans[height].push_back(root->val); 10 dfs(root->left, height + 1); 11 dfs(root->right, height + 1); 12 } 13 14 public: 15 vector<vector<int>> levelOrderBottom(TreeNode* root) { 16 dfs(root, 0); 17 reverse(ans.begin(), ans.end()); 18 return ans; 19 } 20 };
非递归:
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>> resultVec; 14 if(!root) 15 return resultVec; 16 int parentSize = 1, childSize = 0; 17 int level = 0; 18 TreeNode *temp; 19 queue<TreeNode*> nodes; 20 nodes.push(root); 21 resultVec.push_back(vector<int>()); 22 while(!nodes.empty()) 23 { 24 temp = nodes.front(); 25 resultVec[level].push_back(temp->val); 26 nodes.pop(); 27 if(temp->left) 28 { 29 nodes.push(temp->left); 30 childSize++; 31 } 32 if(temp->right) 33 { 34 nodes.push(temp->right); 35 childSize++; 36 } 37 parentSize--; 38 if(parentSize == 0) 39 { 40 parentSize = childSize; 41 childSize = 0; 42 level++; 43 resultVec.push_back(vector<int>()); 44 } 45 } 46 resultVec.erase(resultVec.end()-1); 47 reverse(resultVec.begin(),resultVec.end()); 48 return resultVec; 49 } 50 };