首页 > 学院 > 开发设计 > 正文

515. Find Largest Value in Each Tree Row

2019-11-08 02:02:03
字体:
来源:转载
供稿:网友

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]

思路: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> ans; int maxLevel = 0; void dfs(TreeNode* root, int level){ if(root == NULL) return ; else { if(level > maxLevel){ ans.push_back(root->val); maxLevel = level; } else { if(root->val > ans[level - 1]) ans[level - 1] = root->val; } dfs(root->left, level + 1); dfs(root->right, level + 1); } } vector<int> largestValues(TreeNode* root) { dfs(root, 1); return ans; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表