题目:
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]
题意是输入一个二叉树,找出二叉树中每一行的最大值。要找出每行所有节点中的最大值,想到的方法就是利用队列进行层次遍历。通过层次遍历来找出最大值,关键是怎样将不同行的节点分隔开来,办法是通过一个空指针将不同的行节点分隔开来(注意:添加标志前应该判断是否还有节点未遍历)。
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> res;
if(root == nullptr)
return res;
queue<TreeNode*> qi;
TreeNode* flag = nullptr;//分隔的标志
qi.push(root);
qi.push(flag);
int nMax = INT_MIN;
while(!qi.empty()){
if(qi.front() == flag){//若遍历完一行的节点
qi.pop();
res.push_back(nMax);
nMax = INT_MIN;//重置初值
if(!qi.empty())//判断整棵树是否遍历完
qi.push(flag);
}else{
TreeNode* ptr = qi.front();
nMax = max(nMax, ptr->val);
if(ptr->left)
qi.push(ptr->left);
if(ptr->right)
qi.push(ptr->right);
qi.pop();
}
}
return res;
}
};