π One-stop destination for all your technical interview Preparation π
Given the root of a binary tree, return its maximum depth.
A binary treeβs maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Worst case, if tree is skewed then it will take O(N) else O(h) space, where h is the height of the tree.
class Solution{
public:
int maxDepth(TreeNode *root){
if (root == NULL) return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
class Solution{
public:
int maxDepth(TreeNode *root){
if (root == NULL) return 0;
queue<TreeNode *> q;
q.push(root);
int depth = 0;
while (!q.empty()) {
int sz = q.size();
for (int i = 0; i < sz; i++) {
TreeNode *node = q.front();
q.pop();
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
}
depth++;
}
return depth;
}
};