算法分析与设计课程作业第四周#1
上周挑选了一道有关深度优先搜索的medium题来做,这次就根据宽度优先搜索的标签选了一道有关宽度优先搜索的medium题,以下就是题目:
515. Find Largest Value in Each Tree Row
You need to find the largest value in each row of a binary tree.
Example:
Input:
1
/ \
3 2
/ \ \
5 3 9
Output: [1, 3, 9]
思路:
这道题目还挺简洁的,就是找一棵树的每一层的最大数。题目的标签是宽度优先搜索,一开始我却没想到如何从宽度优先搜索的优先队列中区分开每一层的数,倒想到用深度优先搜索能通过递归递增一个depth的变量确定某一层的数是属于哪一层的,就先用深度优先搜索实现了。至于宽度优先搜索,我想到:可以在每一层扩展完所有节点后,记录队列长度,此时因为本层节点都已出列,队列中的都是下一层节点且包含全部下一层节点,即可根据这一记录(进行记录的队列长度次数的出列)统计出下一层的最大数,完成上次记录的队列长度次数的出列后,再算一次当时队列长度,即得到下下层的节点数,如此类推,直到队列为空为止。
代码块
这次除了些手误,没犯什么错误,就直接将自己的代码放在下面吧。
深度优先搜索:
/**
* 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:
void traverse(TreeNode* root, int depth, vector<int>& max){
if(root == NULL){
return ;
}
if(max.size() <= depth){
max.push_back(root->val);
}
else{
max[depth] = max[depth] > root->val?max[depth] : root->val;
}
if(root->left != NULL) traverse(root->left, depth + 1, max);
if(root->right != NULL) traverse(root->right, depth + 1, max);
}
vector<int> largestValues(TreeNode* root) {
vector<int> result;
traverse(root, 0, result);
return result;
}
};
宽度优先搜索:
/**
* 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<int> largestValues(TreeNode* root) {
vector<int> result;
if(root == NULL){
return result;
}
queue<TreeNode*> row;
row.push(root);
while(!row.empty()){
int rowsize = row.size();
int max = row.front()->val;
while(rowsize--){
TreeNode* temp = row.front();
max = max > temp->val?max:temp->val;
row.pop();
if(temp->left != NULL) row.push(temp->left);
if(temp->right != NULL) row.push(temp->right);
}
result.push_back(max);
}
return result;
}
};