104. Maximum Depth of Binary Tree
题目描述
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.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
方法1
递归解法
class Solution {
public:
int maxDepth(TreeNode *root) {
if(!root) return 0;
if(!root->left)
return maxDepth(root->right)+1;
if(!root->right)
return maxDepth(root->left)+1;
return max(maxDepth(root->left),maxDepth(root->right))+1;
}
};
方法2
树的层次遍历
class Solution {
public:
int maxDepth(TreeNode *root) {
if(root==nullptr)
return 0;
queue<TreeNode*> q;
q.push(root);
int depth=0;
while(!q.empty())
{
//我们将这一层有节点触发depth的更新
//而我们对depth的更新放在了进入循环的开始部分
//所以depth合理的初始化为了0
depth++;
int n = q.size();
while(n--)
{
TreeNode * currentNode =q.front();
q.pop();
if(currentNode->left!=nullptr)
q.push(currentNode->left);
if(currentNode->right!=nullptr)
q.push(currentNode->right);
}
}
return depth;
}
};