一、返回高度
一棵树的高度如下:
思路:
利用递归的思想:
如果一棵树是空树,那么返回0;
如果不是空树,进行以下步骤:
1、记录结点本身,并将高度赋为1;
2、记录结点左子树的高度和右子树的高度,取左右子树高度的最大值,记为max;
3、结果即为max+1。
以上是一个递归过程。
递归出口:结点为NULL,则返回0.
代码:
//树的高度
int get_height(Node* node)
{
if (node == NULL)
{
return 0;
}
else
{
int left_h = get_height(node->left);
int right_h = get_height(node->right);
int max = left_h;
if (right_h > max)
{
max = right_h;
}
return max + 1;
}
}
二、返回最大值
思路:
仍然是递归的思想:遍历到空结点为止。
始终返回结点的(本值,左子树最大值,右子树最大值)三者中的最值,就是树的最大值。
代码:
//二叉树的最大值
int get_maximum(Node* node)
{
if (node == NULL)
{
return -1;
}
else
{
int left = get_maximum(node->left);
int right = get_maximum(node->right);
int self = node->data;
int max = left;
if (right > max)
{
max = right;
}
if (self > max)
{
max = self;
}
return max;
}
}