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] 解决方法:题目要求是要输出一个二叉树中每层的最大数。这是一个典型的二叉树层序遍历的问题,需要使用队列来解决,用队列queue实现广度优先搜索,将i层的数存到队列中,并且在i+1层数字入队的过程中进行i层的比较。当i+1的数存完之后,也就比较完了i层每一个数从而得到i层最大的数,并存到结果的vector中。对这棵二叉树的每一层都进行这样的操作,到了最后一层也就得到输出结果。 首先读取当前队列的大小存在count中,当count不为0的时候,我们将提取队列的队首元素front(),将它的左右子节点存到队列的队尾,并且队列的队首出队,count减1;如果count为0,就说明i+1层的数字已经全部存到了队列中并且i层的每一个数字已经进行了比较。
代码如下:
class Solution { public: vector<int> largestValues(TreeNode* root) { vector<int> ans; if(!root)
return ans; queue<TreeNode*> q; q.push(root); int count, num; TreeNode* node; while(!q.empty()){ num = INT_MIN;
count = q.size(); //读取当前队列大小
while(count){ node = q.front(); if(num < node->val) num = node->val; if(node->left) q.push(node->left); if(node->right) q.push(node->right); q.pop(); count --; } ans.push_back(num); } return ans; } };