欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

515. Find Largest Value in Each Tree Row

程序员文章站 2022-05-18 20:26:45
...

515. 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]

方法1: 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* root, int level, vector<int> & res) {
        if (!root) return;
        if (level == res.size()) res.push_back({INT_MIN});
        res[level] = max(res[level], root -> val);
        dfs(root -> left, level + 1, res);
        dfs(root -> right, level + 1, res);
        return;
    }
};
相关标签: tree