寻找一棵树每层最大的数,思路用广度优先搜索 BFS。用一个队列实现,每次用curLen记录当前层的节点个数,然后依次取出,维护一个最大值,同时将此节点左右子节点也存到队尾。直到一层所有节点全部计数完毕,然后存到向量中,再进行下一层的统计。
/** * 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; if(!root) return res; queue<TreeNode*> q; q.push(root); while(!q.empty()){ int curMax = INT_MIN; const int curLen = q.size(); for(int i = 0; i < curLen; ++i){ TreeNode* cur = q.front(); curMax = max(curMax, cur->val); if(cur->left) q.push(cur->left); if(cur->right) q.push(cur->right); q.pop(); } res.push_back(curMax); } return res; } };