二叉树的最大深度

本文详细解析了求解二叉树最大深度的两种算法:递归法与层序遍历法。通过C++和Java代码实现,帮助读者理解二叉树深度计算的原理及应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

104 二叉树的最大深度

书上的递归法解决(C++)

/**
 * 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) {
        TreeNode* cur = root;
        if(cur == NULL){
            return 0;
        }
        else{
            int i = maxDepth(cur->left);
            int j = maxDepth(cur->right);
            return (i<j)?j+1:i+1;
        }
    }
};

 

由这个题我首先想到的是前几天的层序遍历,把每一层的放在一个链表里面,这个题计算深度就直接统计层数就可以了。

java代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        Queue<TreeNode> que = new LinkedList<>();
        que.offer(root);
        int count = 0,level = 0;
        TreeNode cur = null;
        while(!que.isEmpty()){
            count = que.size();
            level++;
            while(count>=1){
                cur = que.poll();
                if(cur.left != null){
                    que.offer(cur.left);
                }
                if(cur.right != null){
                    que.offer(cur.right);
                }
                count--;
            }
        }
        return level;
    }
}

C++代码:

/**
 * 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;
        }
        int level = 0;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            int count = q.size();
            level++;
            while(count > 0){
                TreeNode* cur = q.front();
                
                q.pop();
                
                if(cur->left != NULL){
                    q.push(cur->left);
                }
                if(cur->right != NULL){
                    q.push(cur->right);
                }
                count--;
            }
        }
        return level;
    }
};

转载于:https://www.cnblogs.com/dong973711/p/10865239.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值