515. Find Largest Value in Each Tree Row

来源:互联网 发布:mac 安装sass 编辑:程序博客网 时间:2024/06/18 18:25

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,这时可以将向量的大小与树的深度进行比较(由于根的深度为0,因此需要加1 比较)用以约束比较的范围,例如根的深度为0,此时向量保存一个数值,即根的值1,在第二层,此时向量大小为1,树的深度+1为2,1<2说明为储存一个数,因此将3储存,向量大小为2.遍历右子树,树的深度+1为2,向量大小为2,此时只需比较新加入的数和此时结点值的大小即可
/** * 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> ans;        if(root==NULL)        return ans;        ans.push_back(root->val);        search(root->right,ans,0+1);        search(root->left,ans,0+1);        return ans;    }    void search(TreeNode* root,vector<int>&a,int depth)    {        if(root==NULL)        return ;        if(a.size()<depth+1)        a.push_back(root->val);        else        a[depth]=max(a[depth],root->val);        search(root->right,a,depth+1);        search(root->left,a,depth+1);    }};
0 0
原创粉丝点击