day 9: 104-maximum-depth-of-binary-tree

This commit is contained in:
Kaushik Narayan R 2023-10-06 12:44:27 -07:00
parent df64aaced5
commit 01f1ea79b0
3 changed files with 50 additions and 0 deletions

View File

@ -0,0 +1,13 @@
#include "soln.hpp"
int main() {
TreeNode n7 = TreeNode(7);
TreeNode n15 = TreeNode(15);
TreeNode n20 = TreeNode(20, &n15, &n7);
TreeNode n9 = TreeNode(9);
TreeNode n3 = TreeNode(3, &n9, &n20);
int answer = 3;
Solution soln;
cout << "Found depth correctly? " << soln.test(&n3, answer) << endl;
return 0;
}

View File

@ -0,0 +1,18 @@
#include "soln.hpp"
int Solution::max(int a, int b)
{
return a > b ? a : b;
}
int Solution::maxDepth(TreeNode *root)
{
if (root == nullptr)
{
return 0;
}
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
bool Solution::test(TreeNode *root, int answer)
{
return maxDepth(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 max(int a, int b);
int maxDepth(TreeNode *root);
bool test(TreeNode *root, int answer);
};