计算二叉树的深度

#include <iostream>  

// 定义二叉树节点  
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

// 递归函数来计算二叉树的深度  
int maxDepth(TreeNode* root) {
    if (root == nullptr) {
        // 空树深度为0  
        return 0;
    }
    else {
        // 递归计算左子树和右子树的深度,取较大值加1(加上当前节点这一层)  
        int leftDepth = maxDepth(root->left);
        int rightDepth = maxDepth(root->right);
        return std::max(leftDepth, rightDepth) + 1;
    }
}

// 辅助函数来构建测试二叉树  
TreeNode* createTestTree() {
    // 创建一个简单的二叉树  
    //       1  
    //      / \  
    //     2   3  
    //    / \  
    //   4   5  
    TreeNode* root = new TreeNode(1);
    root->left = new TreeNode(2);
    root->right = new TreeNode(3);
    root->left->left = new TreeNode(4);
    root->left->right = new TreeNode(5);
    return root;
}

int main() {
    // 创建测试二叉树  
    TreeNode* root = createTestTree();

    // 计算并输出二叉树的深度  
    int depth = maxDepth(root);
    std::cout << "The depth of the binary tree is: " << depth << std::endl;

    // 清理动态分配的内存(为了简单起见,这里没有完整展示内存释放代码)  

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值