昨天晚上参加微软的校招实习笔试,就没有来得及刷leetcode,也没有更新博客。
这道题目其实考察的是递归思想和深度优先遍历。题目本身不难,但是细节不注意就会出错。
附上C++代码:
/**
* 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:
int depth(TreeNode* root){
if(root == NULL)
return 0;
else
return max(depth(root->left), depth(root->right))+1;
}
void DFS(vector<vector<int>> &ans, TreeNode* root, int root_depth){
if(root == NULL)
return;
//if(ans.size() == root_depth){
// ans.push_back(vector<int>());
//}
ans[root_depth].push_back(root->val);
DFS(ans, root->left, root_depth-1);
DFS(ans, root->right, root_depth-1);
}
vector<vector<int>> levelOrderBottom(TreeNode* root) {
int d = depth(root);
vector<vector<int>> ans(d, vector<int>{});
DFS(ans, root, d-1);
return ans;
}
};
/*
int depth(TreeNode *root) {
if (!root) return 0;
return max(depth(root->left),depth(root->right))+1;
}
void levelOrder(vector<vector<int>> &ans, TreeNode *node, int level) {
if (!node) return;
ans[level].push_back(node->val);
levelOrder(ans,node->left,level-1);
levelOrder(ans,node->right,level-1);
}
vector<vector<int>> levelOrderBottom(TreeNode* root) {
int d = depth(root);
vector<vector<int>> ans(d,vector<int> {});
levelOrder(ans,root,d-1);
return ans;
}
*/
/*解法二:
class Solution {
public:
vector<vector<int>> ans;
void DFS(TreeNode* root, int level){
if(root == NULL)
return;
while(ans.size()<=level){
ans.push_back(vector<int>());
}
ans[level].push_back(root->val);
DFS(root->left, level+1);
DFS(root->right, level+1);
}
vector<vector<int>> levelOrderBottom(TreeNode* root) {
DFS(root, 0);
reverse(ans.begin(), ans.end());
return ans;
}
};
*/
/*解法三:
class Solution {
public:
vector<vector<int>> ans;
void DFS(TreeNode* root, int level){
if(root == NULL)
return;
if(ans.size()==level){
ans.push_back(vector<int>());
}
ans[level].push_back(root->val);
DFS(root->left, level+1);
DFS(root->right, level+1);
}
vector<vector<int>> levelOrderBottom(TreeNode* root) {
DFS(root, 0);
reverse(ans.begin(), ans.end());
return ans;
}
};
*/