输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回它的最大深度 3 。
题解1:递归
/**
* 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==NULL)
return 0;
return max(maxDepth(root->left),maxDepth(root->right))+1;
}
};
题解2:层次遍历
/**
* 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==NULL)
return 0;
queue<TreeNode*> qu;
qu.push(root);
int res=0;
while(!qu.empty())
{
int n=qu.size();
//每遍历一层树的高度加一
while(n--)
{
TreeNode* p=qu.front();
qu.pop();
if(p->left!=NULL)
{
qu.push(p->left);
}
if(p->right!=NULL)
{
qu.push(p->right);
}
}
res++;
}
return res;
}
};