三:求深度(高度, 层数)

来源:互联网 发布:java excel合并行 编辑:程序博客网 时间:2024/05/18 02:45

1:求二叉树的深度

思路:递归分别求出左右子树的深度, 取其中的最大值

//从0开始,得到树的深度 int BTreeHeight( BTNode *p){if( p==NULL ) return 0;//获得p的左子树,右子树的深度(都不含p),然后分别加1,表示从p开始,到左子树末端的深度,和到右子树末端的深度;二者取最大值 return MAX(BTreeHeight(p->left)+1,BTreeHeight(p->right )+1);}

2:求某个值为x的节点的深度

//求二叉树中节点值为x的节点的深度 int Height(BTNode *p, int x, int h){int high;if( p->data==x ) return h;if( p==NULL ) return 0;else{    high=Height(p->left, x, h+1);//在左子树中查找     if( high!=0 ) return high;//在左子树中找到了,返回 else  return Height(p->right, x, h+1);//在左子树中未找到, 继续在右子树中查找}} 




原创粉丝点击