1 递归
具体做法:
step 1:对于每个节点,若是不为空才能累计一次深度,若是为空,返回深度为0.
step 2:递归分别计算左子树与右子树的深度。
step 3:当前深度为两个子树深度较大值再加1。
int maxDepth(TreeNode* root) {
if(root == NULL) return 0;//空节点没有深度
return max(maxDepth(root->left),maxDepth(root->right))+1;//返回子树深度+1
}
复杂度分析:
时间复杂度:O(n),其中nnn为二叉树的节点数,遍历整棵二叉树;
空间复杂度:O(n),最坏情况下,二叉树化为链表,递归栈深度最大为n;
2 层次遍历,每层遍历结束,res+1
int maxDepth(TreeNode* root) {
//空节点没有深度
if(root == NULL)
return 0;
//队列维护层次后续节点
queue<TreeNode*> q;
//根入队
q.push(root);
//记录深度
int res = 0;
//层次遍历
while(!q.empty()){
//记录当前层有多少节点
int n = q.size();
//遍历完这一层,再进入下一层
for(int i = 0; i < n; i++){
TreeNode* node = q.front();
q.pop();
//添加下一层的左右节点
if(node->left)
q.push(node->left);
if(node->right)
q.push(node->right);
}
//深度加1
res++;
}
return res;
}
复杂度分析:
时间复杂度:O(n),其中n为二叉树的节点数,遍历整棵二叉树;
空间复杂度:O(n),辅助队列的空间最坏为n;