剑指offer Leetcode 55-I 二叉树的深度
发布日期:2021-05-06 23:39:40 浏览次数:18 分类:精选文章

本文共 991 字,大约阅读时间需要 3 分钟。

image-20201217104735893

解法1:递归

思路:

​ 当前节点的深度 = 左子和右子深度的最大值 + 1

复杂度:

​ ●时间:O(N)

​ ●空间:O(N)

代码:

class Solution {   public:    int maxDepth(TreeNode* root) {           if(root == NULL)            return 0;        return max(maxDepth(root->left), maxDepth(root->right)) + 1;    }};

解法2:层序遍历

思路:

​ 求二叉树的深度 = 求二叉树有多少层,所以用层序遍历就好了

复杂度:

​ ●时间:O(N)

​ ●空间:O(N),当树平衡时,队列queue同时存储N/2个节点。

代码:

class Solution {   public:    int maxDepth(TreeNode* root) {           if(root == NULL)            return 0;        queue
my_queue; my_queue.push(root); int ans = 0; while(!my_queue.empty()){ //用size控制每层 int size = my_queue.size(); while(size--){ TreeNode* cur = my_queue.front(); my_queue.pop(); if(cur->left != NULL) my_queue.push(cur->left); if(cur->right != NULL) my_queue.push(cur->right); } //每层ans + 1 ans++; } return ans; }};
上一篇:website_EM_Website.xml--EM Website does not exist
下一篇:HOST policy-Exec stack

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2025年03月26日 10时53分02秒