【Day-27满就是快】代码随想录-二叉树-二叉树的最大深度

本文介绍了如何使用递归法(包括前序和后序遍历)以及迭代法(如层序遍历)来计算二叉树的最大深度,同时提及了扩展至N叉树的情况。
摘要由CSDN通过智能技术生成

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

————————————————————————————————————

1. 递归法

可以使用前序和后序遍历。前序就是求深度,后续就是求高度。

使用后序遍历来计算树的高度。

精简之后:

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

    int maxDepth(TreeNode* root) {
        return getDepth(root);
    }
};

前序遍历,体现回溯过程:

class Solution {
public:
    int result = 0;
    void getdepth(TreeNode* node, int depth){
        result = depth > result ? depth : result;
        if(node->left == nullptr && node->right == nullptr) return;
        if(node->left){
            depth++; //深度+1
            getdepth(node->left, depth);
            depth--; //回溯深度-1
        }
        if(node->right){
            depth++;
            getdepth(node->right, depth);
            depth--;
        }
        return;
    }

    int maxDepth(TreeNode* root) {
        result = 0;
        if(root == nullptr) return result;
        getdepth(root, 1);
        return result;
    }
};

2. 迭代法

层序遍历最为合适,遍历的层数就是最大深度。

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root == nullptr) return 0;
        int depth = 0;
        queue<TreeNode*> que;
        que.push(root);
        while(!que.empty()){
            depth++;
            int size = que.size();
            for(int i=0;i<size;i++){
                TreeNode* node = que.front();
                que.pop();
                if(node->left) que.push(node->left);
                if(node->right) que.push(node->right);
            }
        }
        return depth;
    }
};

拓展题:N叉数的最大深度

迭代法:

递归法:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值