zAssignments #

Created Wednesday 05 February 2020

Why do we use a queue?

For choosing the data structure: Think about the fundamental operations and the philosophy. We can combine things.

For minimizing work, we can return pair of objects when needed. So that we don’t have to do work again and again. Kind of a dynamic programming approach.

int diameterOfBinaryTree(TreeNode* root) { return diameterOfBinaryTreehelper(root).first; }

pair<int, int> diameterOfBinaryTreehelper(TreeNode* root) { if(root==NULL) { pair<int, int> ret(0, 0); return ret; } pair<int, int> dhleft = diameterOfBinaryTreehelper(root->left); pair<int, int> dhright = diameterOfBinaryTreehelper(root->right);

// check if max diameter is > h1 + h2 // diameter = max(diameter1, diameter2, h1+h2) // height = max pair <int, int> ret; ret.first = max(dhleft.first, max(dhright.first, dhleft.second+dhright.second));// diameter ret.second = 1+max(dhleft.second, dhright.second); return ret; }