LeetCode 515. Find Largest Value in Each Tree Row

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]

题意:


给你一颗二叉树,求每一层的最大值


代码:


/**
 * 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:
    //从根结点开始往下进行搜索,记录下每个节点的深度
    void bfs(TreeNode*& root,int level,vector &res){
        if(!root)return ;
        if(res.size()val);
        else{
            if(res[level]val)//否则就更新为当前节点的值与数组中当前深度的值的最大值
                   res[level]=root->val;
        }
        if(root->left)bfs(root->left,level+1,res);//继续往下一层搜索
        if(root->right)bfs(root->right,level+1,res);
    }
    vector largestValues(TreeNode* root) {
        vectorres;
        bfs(root,0,res);
        return res;
    }
};


你可能感兴趣的:(LeetCode)