LeetCode Find Largest Value in Each Tree Row

LeetCode 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]

给定一棵二叉树,找出每层的最大值。 简单题,直接BFS,在每一层找最大值。代码如下: [cpp] class Solution { public: vector<int> largestValues(TreeNode* root) { vector<int> ans; if (!root)return ans; queue<TreeNode*> q; q.push(root); while (!q.empty()) { int largest = INT_MIN, n = q.size(); while (n–) { TreeNode* front = q.front(); q.pop(); largest = max(largest, front->val); if (front->left)q.push(front->left); if (front->right)q.push(front->right); } ans.push_back(largest); } return ans; } }; [/cpp] 本代码提交AC,用时13MS。]]>

Leave a Reply

Your email address will not be published. Required fields are marked *