-
题目:剑指Offer55-Ⅰ.二叉树的深度
输入一个二叉树,求二叉树的深度(即节点的最大深度最下层叶子节点的深度根节点的高度) -
思路:
求高度:后序遍历 或 层序遍历;求深度:前序遍历
1.递归后序遍历:时间O(n),一般情况O(h),h为二叉树的深度,最坏情况,当退化为单链表时,递归深度为n层,空间 O(n)
class Solution {
public:
int res;
int dfs(TreeNode* root) {
if (!root) return 0;
int lheight = dfs(root->left), rheight = dfs(root->right);
return max(lheight, rheight) + 1;
}
int maxDepth(TreeNode* root) {
return dfs(root);
}
};
2.层序遍历:时间O(n):每个节点都要处理一次,空间O(n):当二叉树为满二叉树时,队列最多需要同时存n/2个节点;
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root) return 0;
queue<TreeNode*> q;
q.push(root);
int res = 0;//记录层数
while (!q.empty()) {
++res;//累计层数
int size = q.size();
for (int i = 0; i < size; ++i) {
auto tmp = q.front();
q.pop();
if (tmp->left) q.push(tmp->left);
if (tmp->right) q.push(tmp->right);
}
}
return res;
}
};