二叉树递归特性可以计算出二叉树高度:
不多逼逼,code:
#includeusing namespace std;
typedef struct BinaryTreeNode
{
char data; //数据
struct BinaryTreeNode *left; //左孩子
struct BinaryTreeNode *right; //右孩子
}Node;
int getDepth(Node *root)
{
if (NULL == root)
{
return 0;
}
int leftDepth = getDepth(root->left); // 计算左子树的高度,如果为NULL,高度为0
int rightDepth = getDepth(root->right); // 计算右子树的高度,如果为NULL,高度为0
int treeDepth = leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
return treeDepth;
}
int main()
{
//准备数据
Node nodeA = { 'A',NULL,NULL };
Node nodeB = { 'B',NULL,NULL };
Node nodeC = { 'C',NULL,NULL };
Node nodeD = { 'D',NULL,NULL };
Node nodeE = { 'E',NULL,NULL };
Node nodeF = { 'F',NULL,NULL };
Node nodeG = { 'G',NULL,NULL };
//建立关系
nodeA.left = &nodeB;
nodeA.right = &nodeC;
nodeB.left = &nodeD;
nodeB.right = &nodeE;
nodeC.left = &nodeF;
nodeC.right = &nodeG;
//调用函数
int depth = getDepth(&nodeA);
printf("二叉树的深度为:%d\n", depth);
system("pause");
return 0;
}
二叉树,还是这棵二叉树:
运行结果: