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.
BFS或 DFS
/**
* 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) //BFS
{
return maxD(root);
}
int maxD(TreeNode* root)
{
if (root == nullptr)
return 0;
return max(maxD(root->right)+1,maxD(root->left)+1);
}*/
int maxDepth(TreeNode* root) //DFS
{
queue<TreeNode*> q;
int maxlen = 0;
TreeNode* node = root;
if(node==nullptr) return 0;
q.push(node);
while(!q.empty())
{
int size = q.size();
while(size-- >0)
{
if(q.front()->left)
q.push(q.front()->left);
if(q.front()->right)
q.push(q.front()->right);
q.pop();
}
maxlen++;
}
return maxlen;
}
};