leetcode 515. Find Largest Value in Each Tree Row

冷不防 2022-06-13 00:28 266阅读 0赞

1.题目

找出一棵二叉树,每层节点的最大值
You need to find the largest value in each row of a binary tree.

Example:
Input:

  1. 1
  2. / \
  3. 3 2
  4. / \ \
  5. 5 3 9

Output: [1, 3, 9]

2.分析

考察树的遍历,这里按层遍历比较直观。BFS

3.代码

  1. class Solution {
  2. public:
  3. vector<int> largestValues(TreeNode* root) {
  4. vector<int> maxs;
  5. if (root == NULL)
  6. return maxs;
  7. queue<pair<TreeNode*,int>> nodes;
  8. nodes.push(pair<TreeNode*,int>(root,0));
  9. maxs.push_back(root->val);
  10. while (!nodes.empty()) {
  11. root = nodes.front().first;
  12. int level = nodes.front().second;
  13. nodes.pop();
  14. if (level+1 > maxs.size())
  15. maxs.push_back(root->val);
  16. else
  17. maxs[level] = maxs[level] < root->val ? root->val : maxs[level];
  18. if (root->left)
  19. nodes.push(pair<TreeNode*, int>(root->left, level + 1));
  20. if (root->right)
  21. nodes.push(pair<TreeNode*, int>(root->right, level + 1));
  22. }
  23. return maxs;
  24. }
  25. };

发表评论

表情:
评论列表 (有 0 条评论,266人围观)

还没有评论,来说两句吧...

相关阅读