0% found this document useful (0 votes)
138 views46 pages

Tree Striver Notes

data structures and algorithms

Uploaded by

ballistic.code
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
138 views46 pages

Tree Striver Notes

data structures and algorithms

Uploaded by

ballistic.code
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

return -1 if it is not balanced and return height of the tree is it is balanced

// Function to calculate the height of


// the tree and update the diameter
int height(Node* node, int& diameter) {

if (!node) {
return 0;
}

int lh = height(node->left, diameter);


int rh = height(node->right, diameter);

diameter = max(diameter, lh + rh);

return 1 + max(lh, rh);


}
};
class Solution {
public:
vector<vector<int>> verticalTraversal(TreeNode* root) {
// vertical =x and level=y
//[x][y]=set of all values at current vertical,level;
map<int,map<int,multiset<int>>> nodes;
//node , pair<vertical,level>
// vertical =x and level=y
queue<pair<TreeNode*,pair<int,int>>> q;
q.push({root,{0,0}});
while(!q.empty())
{
TreeNode* node=q.front().first;
int x=q.front().second.first;
int y=q.front().second.second;
q.pop();
nodes[x][y].insert(node->val);
if(node->left)
q.push({node->left,{x-1,y+1}});
if(node->right)
q.push({node->right,{x+1,y+1}});
}
vector<vector<int>> ans;
for(auto p:nodes)
{
vector<int> col;
for(auto q:p.second)
{
col.insert(col.end(),q.second.begin(),q.second.end());
}
ans.push_back(col);
}
return ans;
then its full binary tree

You might also like