This problem is relatively simple, I use recursion. It should also be possible to use methods such as queue.
Solution 1: Recursion
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void dfs(TreeNode* node, int depth, int &maxDepth) {
if (node) {
if (depth>maxDepth) maxDepth=depth;
dfs(node->left, depth+1, maxDepth);
dfs(node->right, depth+1, maxDepth);
}
}
int maxDepth(TreeNode* root) {
if (!root) return 0;
int maxDepth=1;
dfs(root, 1, maxDepth);
return maxDepth;
}
int main()
{
TreeNode t1(3);
TreeNode t2(9);
TreeNode t3(20);
TreeNode t4(15);
TreeNode t5(7);
t1.left=&t2;
t1.right=&t3;
t3.left=&t4;
t3.right=&t5;
cout<<maxDepth(&t1)<<endl;
return 0;
}