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]
解析:利用队列结构逐行便利二叉树,对于如何区分二叉树的行,则需要维护另外一个队列,记录队列中每个元素的行数
代码:
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
queue<TreeNode *>Tree;
queue<int>path;
vector<int>ans;
if (root==NULL)
return ans;
Tree.push(root);
path.push(1);
int tempans=INT_MIN;
int tempfloor=1;
while(!Tree.empty())
{
root=Tree.front();
if (path.front()==tempfloor)
{
if (root->val>tempans)
{
tempans=root->val;
}
}
else
{
tempfloor=path.front();
ans.push_back(tempans);
tempans=root->val;
}
if (root->left!=NULL)
{
Tree.push(root->left);
path.push(path.front()+1);
}
if (root->right!=NULL)
{
Tree.push(root->right);
path.push(path.front()+1);
}
Tree.pop();
path.pop();
}
ans.push_back(tempans);
return ans;
}
};