Liny_@NotePad

沉迷ACG中

分治法求解二叉树深度

YOYO posted @ 2009年4月29日 08:05 in 【算法】与【数据结构】 with tags 分治 , 3012 阅读

若一个树没有孩子,则它的深度为1;
若一个树只有左孩子,则它的深度就是左孩子的深度+1;
若一个树只有右孩子,则它的深度就是右孩子的深度+1;
若一个树有两个孩子,则它的深度就是两个孩子中较深的那颗深度+1。
由此可以递归得到该树的高度。

  1. #include<iostream>
  2. using namespace std;
  3.  
  4. /*      二叉树数据结构 */
  5. typedef struct node{
  6.         int value;
  7.         struct node * lchild;   // 左子树
  8.         struct node * rchild;   // 右子树
  9. }Node;
  10.  
  11. /*      创建二叉树函数:返回该结点的值 */
  12. Node* create(){
  13.         int v;
  14.         cin>>v;     //       输入结点的值
  15.         if(v==0)return NULL;    //  输入为0时表示该结点为空
  16.         Node* p = new Node;          //   为结点开辟空间
  17.         p->value = v;
  18.         p->lchild = create();   // 创建左子树
  19.         p->rchild = create();   // 创建右子树
  20.         return p;
  21. }
  22.  
  23. /*      计算二叉树深度函数:返回该树的深度 */
  24. int countDepth(Node* p){
  25.         if(p==NULL)return 0;                    //  如果结点为空,深度为0
  26.         int left = countDepth(p->lchild)+1;          //   获得左子树的深度
  27.         int right = countDepth(p->rchild)+1;    //  获得右子树的深度
  28.         return left>right?left:right;   // 树的深度就是左右子树中较深的那颗深度+1
  29. }
  30.  
  31. int main(){
  32.         Node* p = create();               //   创建树
  33.         cout<<countDepth(p)<<endl;      //    输出树的深度
  34.         return 0;
  35. }

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter