mirror of
https://github.com/20kaushik02/leetcode-gulag.git
synced 2025-12-06 06:24:07 +00:00
day 31: 543-diameter-of-binary-tree
This commit is contained in:
parent
69ba49b561
commit
a0dadd9563
17
543-diameter-of-binary-tree/driver.cpp
Normal file
17
543-diameter-of-binary-tree/driver.cpp
Normal 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;
|
||||
}
|
||||
25
543-diameter-of-binary-tree/soln.cpp
Normal file
25
543-diameter-of-binary-tree/soln.cpp
Normal 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;
|
||||
}
|
||||
19
543-diameter-of-binary-tree/soln.hpp
Normal file
19
543-diameter-of-binary-tree/soln.hpp
Normal 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);
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user