求树的高度的算法 怎么计算二叉树高度?
怎么计算二叉树高度?想法:对于非空二叉树,其深度等于左子树的最大深度加1。Intdepth(bintree*t){intdep1,dep2if(t==null)return(0)else{dep1=d
怎么计算二叉树高度?
想法:对于非空二叉树,其深度等于左子树的最大深度加1。
Intdepth(bintree*t)
{
intdep1,dep2
if(t==null)return(0)
else
{
dep1=depth(t->lchild)
dep2=depth(t->rchild)
if(dep1>dep2)return(dep1)
elsereturn(dep2 1)
]~。首先,我们声明一个[treeheight]函数并传递一个[root]树。
2. 然后,我们定义左子树和右子树,称为lcheight和rcheight。
3. 这时,我们可以判断这棵树是否是空的。如果为空,我们可以直接退出函数。
4. 此时,我们可以在这里调用左递归和右递归。
5. 接下来,我们可以在这里递归累加。
6. 注意,第五步的代码与此代码具有相同的功能。