二叉树的高度和深度定义
(对某个节点来说)
深度是指从根节点到该节点的最长简单路径边的条数;
高度是指从最下面的叶子节点到该节点的最长简单路径边的条数;
(对二叉树)
深度是从根节点数到它的叶节点;
高度是从叶节点数到它的根节点;
注意: 树的深度和高度一样,但是具体到树的某个节点,其深度和高度不一样。
如图:树的高度和深度都为4(看层数);
节点8的深度为3;节点9的高度为2;
求二叉树高度深度代码实现:
1.高度:
int high(struct node*root)
{
int h1,h2;
if(root)
{
h1=high(root->left);
h2=high(root->right);
return h1>h2?h1+1:h2+1;
}
else return 0;
}
2.深度
int deep(struct node*root,int num)//num=0;
{
if(root)
{
num++;
if(deep(root->left,num)>deep(root->right,num))
return deep(root->left,num);
else
return deep(root->right,num);
}
else
return num;
}