跳到主要内容

简述C++计算二元树的深度 ?

参考答案:

计算二元树的深度是一个常见的问题,可以通过递归的方式来解决。在C++中,我们可以定义一个递归函数来计算二元树的深度。

首先,我们需要定义二元树的数据结构。一个简单的二元树节点可以定义如下:

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

接下来,我们可以定义一个递归函数来计算二元树的深度:

int maxDepth(TreeNode* root) {
    if (root == NULL) {
        return 0;
    } else {
        int leftDepth = maxDepth(root->left);
        int rightDepth = maxDepth(root->right);
        return max(leftDepth, rightDepth) + 1;
    }
}

在这个函数中,我们首先检查根节点是否为空。如果根节点为空,那么树的深度为0。否则,我们递归地计算左子树和右子树的深度,并返回较大的深度值加1(加1是因为我们需要将根节点纳入考虑范围)。

使用这个函数,我们可以轻松地计算任何给定二元树的深度。例如:

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);

int depth = maxDepth(root);
cout << "The depth of the binary tree is: " << depth << endl;

在这个例子中,我们创建了一个深度为3的二元树,并计算了其深度。输出应为:

The depth of the binary tree is: 3