leetcode -- 515. Find Largest Value in Each Tree Row
生活随笔
收集整理的這篇文章主要介紹了
leetcode -- 515. Find Largest Value in Each Tree Row
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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]
來(lái)源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
?
我的思路:
1. 用廣搜,但是這道題在leetcode上是深搜,我感覺用廣搜好解一點(diǎn),于是選擇廣搜
2. 因?yàn)橐涗浢恳粚又?#xff0c;所以在每次進(jìn)入while循環(huán),先看里面有幾個(gè)元素,就是每一層的結(jié)點(diǎn)個(gè)數(shù)
3. 然后再在每層中找最大值即可
/*** 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:queue<TreeNode*> q; //存放值vector<int> maxValue;vector<int> largestValues(TreeNode* root) {if(root==NULL) return maxValue;q.push(root);while(!q.empty()){int size = q.size();int maxnV = INT_MIN;for(int i = 0; i < size; i++){TreeNode* front = q.front();int v = front->val; //隊(duì)頭的值maxnV = max(maxnV, v);q.pop();if(front->left) q.push(front->left);if(front->right) q.push(front->right);}maxValue.push_back(maxnV); }return maxValue;} };?
?
總結(jié)
以上是生活随笔為你收集整理的leetcode -- 515. Find Largest Value in Each Tree Row的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: leetcode -- 279. Per
- 下一篇: leetcode -- 357. Cou