BFS or DFS 练习题
C++ 代码
BFS
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> res;
if(!root)return res;
queue<TreeNode*> q;
q.push(root);
while(q.size()) {
int sz = q.size();
res.push_back(INT_MIN);
while(sz--) {
auto t = q.front();
res.back() = max(res.back(), t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
q.pop();
}
}
return res;
}
};
DFS
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
dfs(root, 0);
return res_;
}
void dfs(TreeNode* root, int depth) {
if(!root)return;
// 该层首次添加
if(res_.size() == depth) {
res_.push_back(root->val);
}
// 其他子树遍历到该层进行迭代
res_[depth] = max(res_[depth], root->val);
dfs(root->left, depth+1);
dfs(root->right, depth+1);
}
private:
vector<int> res_;
};