在下面的代码中,我使用std :: map& myMap作为参考
我使用map值dataNode来更新start_time和end_time的值,但我看到这些值没有更新,我得到了
打印时在widthOfBinaryTree中打印
0 2147483647 -2147483648
1 2147483647 -2147483648
2 2147483647 -2147483648
为什么start_time和end_time的值不会在树的每个级别都得到更新。
class Solution {
public:
typedef struct dataNode
{
int start_time =INT_MAX;
int end_time = INT_MIN;
};
int widthOfBinaryTreeRecursion(TreeNode* root, int level, int sideLevel, bool left, std::map<int ,dataNode>&myMap)
{
if(root == nullptr)
{
return 0 ;
}
auto element = myMap[level];
widthOfBinaryTreeRecursion(root->left , level+1 , sideLevel*2 , true ,myMap);
if(left && sideLevel < element.start_time)
{
cout << "start" << " " <<element.start_time << " " << sideLevel << " " <<root->val <<" " << level <<endl;
element.start_time = sideLevel;
}
if(!left && sideLevel > element.end_time)
{
cout <<"end" <<" " << element.end_time << " " << sideLevel << " " <<root->val <<" " << level <<endl;
element.end_time = sideLevel;
}
widthOfBinaryTreeRecursion(root->right, level+1 ,sideLevel*2+1, false, myMap);
return 0;
}
int widthOfBinaryTree(TreeNode* root)
{
std::map<int , dataNode>myMap;
widthOfBinaryTreeRecursion(root, 0, 1, true,myMap);
for(auto itr : myMap)
{
cout << itr.first <<" " << itr.second.start_time << endl;
}
return 0;
}
};
答案 0 :(得分:1)
这会创建值的本地副本,因此您对其所做的任何更改都不会反映在地图中:
auto element = myMap[level];
由于您打算修改地图中存储的值,您应该获得auto &
的共享引用:
auto & element = myMap[level];