LeetCode 515. Find Largest Value in Each Tree Row

来源:互联网 发布:网络的3类地址 编辑:程序博客网 时间:2024/06/06 03:51

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<int> &res){        if(!root)return ;        if(res.size()<level+1)//如果当前深度的节点在数组中还没有记录的话,将该节点的值存入数组            res.push_back(root->val);        else{            if(res[level]<root->val)//否则就更新为当前节点的值与数组中当前深度的值的最大值                   res[level]=root->val;        }        if(root->left)bfs(root->left,level+1,res);//继续往下一层搜索        if(root->right)bfs(root->right,level+1,res);    }    vector<int> largestValues(TreeNode* root) {        vector<int>res;        bfs(root,0,res);        return res;    }};


阅读全文
0 0
原创粉丝点击