算法分析與設計課程作業第四周#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;
}
};