给定一棵二叉树的根节点 root
,请找出该二叉树中每一层的最大值。
示例1:
示例2:
提示:
- 二叉树的节点个数的范围是
[0,104]
-231 <= Node.val <= 231 - 1
C++
class Solution { public: vector<int> largestValues(TreeNode* root) { vector<int> res; dfs(root, res, 0); return res; } void dfs(TreeNode* root, vector<int>& res, int currHeight){ if(!root) return; if(res.size() == currHeight){ res.push_back(root -> val); } res[currHeight] = max(root -> val, res[currHeight]); dfs(root -> left, res, currHeight + 1); dfs(root -> right, res, currHeight + 1); } };
|