二叉树深度计算

二叉树的遍历方法分为深度优先遍历和广度优先遍历,深度优先遍历又分为先序遍历中序遍历和后序遍历。

深度优先遍历计算

深度优先遍历主要采用递归的方式计算,把要计算的二叉树分为左子树和右子树,每递一次深度加1,最后比较左子树和右子树的深度取最大+1

实现

我们先定义一个二叉树结构体

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

接下来的二叉树用的都是这个结构体。

通过递归计算左右子树的最大深度,逐层向上返回结果

  • 终止条件:空节点深度为 0。
  • 递归逻辑:当前节点深度 = max(左子树深度, 右子树深度) + 1。
#include <algorithm>

int maxDepth(TreeNode* root) {
    if (root == nullptr) return 0;  // 空节点深度为0
    int left = maxDepth(root->left);
    int right = maxDepth(root->right);
    return std::max(left, right) + 1;  // 返回较大子树深度+1
}

 广度优先遍历计算

核心原理

广度优先遍历采用迭代的方式实现,通过层序遍历统计树的层数(即深度)

  • 使用队列逐层遍历节点。
  • 每遍历完一层,深度加 1。

实现 

#include <queue>

int maxDepth(TreeNode* root) {
    if (!root) return 0;
    std::queue<TreeNode*> q;
    q.push(root);
    int depth = 0;
    
    while (!q.empty()) {
        int size = q.size();
        depth++;  // 每层深度+1
        for (int i = 0; i < size; ++i) {
            TreeNode* node = q.front();
            q.pop();
            if (node->left) q.push(node->left);
            if (node->right) q.push(node->right);
        }
    }
    return depth;
}

 测试用例

int main() {
    // 构建示例二叉树:深度为3
    //       1
    //      / \
    //     2   3
    //        / \
    //       4   5
    TreeNode* root = new TreeNode(1);
    root->left = new TreeNode(2);
    root->right = new TreeNode(3);
    root->right->left = new TreeNode(4);
    root->right->right = new TreeNode(5);

    // 测试递归法
    std::cout << "递归法深度: " << maxDepth(root) << std::endl;  // 输出3

    // 测试迭代法
    std::cout << "迭代法深度: " << maxDepth(root) << std::endl;  // 输出3

    // 释放内存(实际开发中建议用智能指针)
    delete root->right->right;
    delete root->right->left;
    delete root->right;
    delete root->left;
    delete root;
    
    return 0;
}

### 完全二叉树深度计算方法 完全二叉树深度可以通过其节点总数来推导得出。假设一棵完全二叉树的高度为 \( h \),则该树具有如下特性: - 对于高度为 \( h \) 的完全二叉树,前 \( h-1 \) 层是一个满二叉树,因此这些层中的节点总数为 \( 2^{h-1} - 1 \)[^3]。 - 第 \( h \) 层可能未被填满,但所有节点均集中分布在左侧。 如果已知完全二叉树的总节点数 \( n \),可以根据以下公式计算深度 \( h \): \[ h = \lfloor \log_2(n+1) \rfloor \] 此公式的依据在于完全二叉树的性质以及对数函数的应用[^3]。具体而言,对于任意给定的节点数 \( n \),满足条件 \( 2^{h-1} \leq n < 2^h \) 的整数值 \( h \) 即为其深度。 以下是基于递归实现的一种算法用于动态计算完全二叉树深度: ```c int TreeDeep(struct node *T) { int deep = 0; if (T) { int ld = TreeDeep(T->l); int rd = TreeDeep(T->r); deep = ld >= rd ? ld + 1 : rd + 1; } return deep; } ``` 上述代码片段展示了如何利用递归来解一般二叉树(包括完全二叉树)的深度[^2]。通过比较左右子树的深度并取较大者加一即可得到当前节点所在树的深度。 另外一种更高效的方法适用于完全二叉树场景下快速获取其深度。这种方法依赖于不断向左和右遍历直到叶子节点为止,并记录路径长度作为最终结果的一部分[^4]: ```javascript var countNodes = function(root) { if (root == null) { return 0; } let leftNode = root.left; let rightNode = root.right; let leftDepth = 0; let rightDepth = 0; while (leftNode != null) { leftNode = leftNode.left; leftDepth++; } while (rightNode != null) { rightNode = rightNode.right; rightDepth++; } if (leftDepth === rightDepth) { return Math.pow(2, rightDepth + 1) - 1 ; } let leftNum = countNodes(root.left); let rightNum = countNodes(root.right); return leftNum + rightNum + 1 ; }; ``` 以上JavaScript版本实现了针对完全二叉树特性的优化策略,在某些情况下能够显著减少不必要的递归调用次数从而提升性能表现[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值