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] ]
方法1:分层考虑,直接用vector
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
//每层分开考虑
vector<vector<int>> res;
addValue(0, res,root);
reverse(res.begin(),res.end());
return res;
}
void addValue(int count, vector<vector<int>> &res,TreeNode* root){
if(root==NULL) return;
if(res.size()<count+1) res.push_back({root->val});
else res[count].push_back(root->val);
addValue(count+1,res,root->left);
addValue(count+1,res,root->right);
}
/*单独节点分开考虑的
vector<vector<int>> levelOrderBottom(TreeNode* root) {
map<int,vector<int>> treeValue;
vector<vector<int>> res;
addValue(0,treeValue,root);
for(auto a:treeValue){
res.insert(res.begin(),a.second);
}
return res;
}
void addValue(int count, map<int,vector<int>> &treeValue,TreeNode* root){
if(root==NULL) return;
if(treeValue.count(count)) treeValue.find(count)->second.push_back(root->val);
else treeValue[count]={root->val};
addValue(count+1,treeValue,root->left);
addValue(count+1,treeValue,root->right);
}*/
};
Tips:递归传值时,是count+1,不能用count++,这个会改变当前count的值。
采用了reverse()函数