day 31: 543-diameter-of-binary-tree

This commit is contained in:
Kaushik Narayan R 2023-11-03 09:53:51 -07:00
parent 69ba49b561
commit a0dadd9563
3 changed files with 61 additions and 0 deletions

View File

@ -0,0 +1,17 @@
#include "soln.hpp"
int main()
{
// input
TreeNode n1 = TreeNode(1);
TreeNode n3 = TreeNode(3);
TreeNode n6 = TreeNode(6);
TreeNode n9 = TreeNode(9);
TreeNode n2 = TreeNode(2, &n1, &n3);
TreeNode n7 = TreeNode(7, &n6, &n9);
TreeNode n4 = TreeNode(4, &n2, &n7);
int answer = 4;
Solution soln;
cout << "Found diameter correctly? " << soln.test(&n4, answer) << endl;
return 0;
}

View File

@ -0,0 +1,25 @@
#include "soln.hpp"
int Solution::diameterOfBinaryTree(TreeNode *root)
{
int max_dia = 0;
height(root, max_dia);
return max_dia;
}
int Solution::height(TreeNode *subroot, int &max_dia)
{
if (!subroot)
return 0;
int left_child_height = height(subroot->left, max_dia);
int right_child_height = height(subroot->right, max_dia);
// max_dia for all in this subtree is left_h + right_h, so check global maximum
max_dia = max(max_dia, left_child_height + right_child_height);
// for height, we add the edge connecting this subtree to max of child heights
return 1 + max(left_child_height, right_child_height);
}
bool Solution::test(TreeNode *root, int answer)
{
return diameterOfBinaryTree(root) == answer;
}

View File

@ -0,0 +1,19 @@
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution
{
public:
int diameterOfBinaryTree(TreeNode *root);
int height(TreeNode *subroot, int &max_dia);
bool test(TreeNode *root, int answer);
};