本文主要是介绍力扣515. 在每个树行中找最大值(BFS,DFS),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Problem: 515. 在每个树行中找最大值
文章目录
- 题目描述
- 思路
- 复杂度
- Code
题目描述
思路
思路1:BFS
套用BFS模板,直接在遍历树的某一层时将当前层的最大值存入数组中
思路2:DFS
回溯思想,在递归时不断更新可选列表(根据当前树的层数,也可以抽象看作是回溯思想中的决策阶段)
复杂度
思路1:
时间复杂度:
O ( n ) O(n) O(n);其中 n n n为二叉树节点的个数
空间复杂度:
O ( n ) O(n) O(n)
思路2:
时间复杂度:
O ( n ) O(n) O(n)
空间复杂度:
O ( h e i g h t ) O(height) O(height);其中 h e i g h t height height为二叉树的高度
Code
思路1:
/*** 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:/*** Get the largest values of each level** @param root The root of a binary tree* @return vector<int>*/vector<int> largestValues(TreeNode* root) {if (root == nullptr) {return{};}return levelMaxNumber(root);}/*** BFS* * @param root The root of a binary tree* @return vector<int>*/vector<int> levelMaxNumber(TreeNode* root) {vector<int>res;queue<TreeNode*> queue;int depth = 0;queue.push(root);res.push_back(root -> val);while (!queue.empty()) {int levelMaxNum = INT_MIN;int curLevelSize = queue.size();for (int i = 0; i < curLevelSize; ++i) {TreeNode* curLevelNode = queue.front();queue.pop();if (curLevelNode -> left != nullptr) {TreeNode* nextLeftNode = curLevelNode -> left;queue.push(nextLeftNode);levelMaxNum = max(nextLeftNode -> val, levelMaxNum);}if (curLevelNode -> right != nullptr) {TreeNode* nextRightNode = curLevelNode -> right;queue.push(nextRightNode);levelMaxNum = max(nextRightNode -> val, levelMaxNum);}}if (!queue.empty()) {res.push_back(levelMaxNum);}}return res;}
};
思路2:
/*** 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:/*** Get the largest values of each level** @param root The root of a binary tree* @return vector<int>*/vector<int> largestValues(TreeNode *root) {vector<int> res;if (root == nullptr) {return {};}dfs(res, root, 0);return res;}/*** DFS** @param res Result set* @param root The root of a binary tree* @param curHeight The current height of a binary tree*/void dfs(vector<int> &res, TreeNode *root, int curHeight) {if (curHeight == res.size()) {res.push_back(root->val);} else {res[curHeight] = max(res[curHeight], root->val);}if (root->left) {dfs(res, root->left, curHeight + 1);}if (root->right) {dfs(res, root->right, curHeight + 1);}}
};
这篇关于力扣515. 在每个树行中找最大值(BFS,DFS)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!