二叉树中高度为h的子树

问题描述

我们如何在二叉树中找到高度为“h”的子树的数量函数定义为 int subtree( node *root,int k); 其中 k 是特定高度。

解决方法

首先,我们递归计算树的高度如下:

如果树为空,则高度为0。

如果树不为空,则高度为其子树的最大高度加1。

在 C 中(我假设 OP 基于响应使用 C),这看起来像

typedef struct Node {
    Node* leftChild,node* rightChild
} Node;

typedef Node* Tree;

unsigned int max(unsigned int a,unsigned int b) {
    return a > b ? a : b;
}

unsigned int height(Tree tree) {
    return tree ? 1 + max(height(tree->leftChild,tree->rightChild)) : 0;
}

请注意,一般来说,Node 会有一些额外的数据。但这些数据在此处无关紧要,因此我们不包括在内(尽管如果您愿意,这样做也很容易)。

现在,我们要稍微修改 height 函数。为此,我们定义

typdef struct Result {
    unsigned int height,unsigned int count
} Result;

/**
 * The returned .height should be the height of the tree.
 * The returned .count should be the number of subtrees of tree
 * with height k.
*/
Result resultCountChildren(Tree tree,unsigned int k) {
    if (tree) {
        Result leftResult = resultCountChildren(tree->left,k);
        Result rightResult = resultCountChildren(tree->right,k);
        unsigned int heightOfTree = 1 + max(leftResult.height,rightResult.height);
        unsigned int count = leftResult.count + rightResult.count + (heightOfTree == k);
        Result result = {
            .height = heightOfTree,.count = count
        };
        return result;
    } else {
        unsigned int height = 0;
        unsigned int count = (0 == k);
        Result result = {
            .height = height,.count = count
        };
        return result;
    }
}

unsigned int count(Tree tree,unsigned int k) {
    return resultCountChildren(tree).count;
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...