Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Seen this question in a real interview before? YesNo
depth-first-search
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
breadth-first-search
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) return 0;
queue<TreeNode*> q;
q.emplace(root);
int ret = 0;
while (!q.empty()) {
++ret;
size_t n = q.size();
for (size_t i = 0; i != n; ++i) {
TreeNode* p = q.front();
q.pop();
if (p->left != nullptr) q.emplace(p->left);
if (p->right != nullptr) q.emplace(p->right);
}
}
return ret;
}
};