---
title: "递归小解"
author: "smallearth"
date: "2013-01-08T09:37:00Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2013-11-30T20:10:28Z"
id: 1983299
url: "https://smallearth.iteye.com/blog/1983299"
---

```
 
           2. int BinTreeDepth(BitTree T)
            {
                    if(T==NULL)return0;
                     else{
                              u=BinTreeDepth(T->lchild);
                              v=BinTreeDepth(T->rchild);
                              return((u>v?u:v)+1);
                          }
             }

关于递归，你可以看成是一句一句往下运行嘛。需要保存状态的时候，系统就会自动用栈帮你保存。就依你说得那个为例：
n为全局变量，初值为0；

第一次调用
BinTreeDepth(BitTree T)，假设T！=NULL
由于T!=NULL：跳过if (T==NULL) return 0; 关键到了
BinTreeDepth(BitTree T); 调用本身的函数：此时的T->lchild保存在栈中，既然是调用就得从函数开头执行：
看下这时候T2（其实就是T->lchild），if (T==NULL) return 0；这里假设T不是NULL，就继续运行在遇到u=BinTreeDepth(BitTree T); 在调这个函数本身——
这里就假设它为T->lchild==NULL吧。这下可好，这个函数执行return 0；慢着：第二次函数调用u=BinTreeDepth(BitTree T)中的函数值已经计算出来啦。这时u=0；你还记得第二次调用运行到了v=height(T->rchild); 这句话吧？好，这个过程就和u=height(T->lchild)完全一样。这里也假设得到的v=0则第二次调用到了
 return((u>v?u:v)+1);
得到一个返回值，不如就假设u〉n，于是返回值1；好，这一波完毕；你还记得第一次调用的BinTreeDepth(BitTree T)吧，这时把返回值给u,u=1；然后执行到第一次调用中的v=BinTreeDepth(BitTree T); 了。分析同上。
```