#Leetcode# 515. Find Largest Value in Each Tree Row
发布时间:2020-12-14 04:27:34 所属栏目:大数据 来源:网络整理
导读:https://leetcode.com/problems/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. * str
https://leetcode.com/problems/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> ans; if(!root) return ans; helper(root,ans,1); return ans; } void helper(TreeNode* root,vector<int>& ans,int depth) { if(depth > ans.size()) ans.push_back(root -> val); else ans[depth - 1] = max(ans[depth - 1],root -> val); if(root -> left) helper(root -> left,depth + 1); if(root -> right) helper(root -> right,depth + 1); } }; 今天是不吃宵夜的第二天!!!今天也是被二叉树折磨得死去活来的一天 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |