In the below code I am using std::map&myMap as reference
I am using the map value dataNode to update the values of start_time and end_time but I see that these values are not updated and I get the
following prints in widthOfBinaryTree when I print
0 2147483647 -2147483648
1 2147483647 -2147483648
2 2147483647 -2147483648
Why would not the values of start_time and end_time not get updated at every level of the tree .
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;
}
};
Aucun commentaire:
Enregistrer un commentaire