[LeetCode] 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]
找出二叉树中每一层最大的元素。
思路:利用层次遍历找出每一层最大元素即可。
/** * 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> res; if (root == nullptr) return res; queue<TreeNode*> q; q.push(root); while (!q.empty()) { int n = q.size(); int maxVal = INT_MIN; for (int i = 0; i < n; i++) { TreeNode* node = q.front(); q.pop(); maxVal = max(maxVal, node->val); if (node->left != nullptr) q.push(node->left); if (node->right != nullptr) q.push(node->right); } res.push_back(maxVal); } return res; } }; // 14 ms
思路:使用递归dfs来查找每层最大值。
/** * 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> res; dfs(root, 0, res); return res; } void dfs(TreeNode* node, int height, vector<int>& res) { if (node == nullptr) return; if (height >= res.size()) { res.push_back(node->val); } else { res[height] = max(res[height], node->val); } dfs(node->left, height + 1, res); dfs(node->right, height + 1, res); } }; // 13 ms