二叉树的宽度与高度

来源:互联网 发布:网络教育要不要学 编辑:程序博客网 时间:2024/04/30 07:23
分冶策略.
    1.二叉树的高度
    2.二叉树的宽度
    3.比较两个二叉树是否相等

数据结构的定义

    先定义一个简单的二叉树,由于只是演示,所以定义得比较简单.

<span style="font-size:14px;"> #include <stdio.h> #define MAX(x,y) ((x)>(y)?(x):(y)) //define a binary search tree typedef struct BNode {     int val;    struct BNode *left, *right; }BNode,*BTree;</span>
二叉树节点的值为val,另外为了比较方便还定义了一个宏MAX.// insert a node to binary tree// we assume that no duplicated elementsvoid BTreeInsert(BTree *bt, int val) {    BNode *p = *bt,*cur = *bt;//p is a parent node of cur    while (cur != NULL)   {//find the position to insert node val        p = cur;</span>
      if ( val < cur->val )</span>
        cur = cur->left;        else            cur = cur->right;    }    BNode *n = malloc(sizeof(BNode));    n->val = val;    n->left = n->right = NULL;    if (p == NULL)        *bt = n;// the tree is empty      else    {       if (val < p->val)            p->left = n;         else           p->right = n;   }}//BTreeInsert还定义了一个函数BTreeInsert用来帮助创建二叉树.</span>

二叉树的高度

基本方法:二叉树,分别求出左右子数的高度,然后取左右子树高度的最大数值,再加上1,就是二叉树的高度.
由于该问题又被划分为两个性质一样的子问题,因此很容易导致递归.

39 //get the depth of a BST
40 int BTreeDepth(BTree bt)
41 {
42     if (bt != NULL)
43     {
44         int dep_left = BTreeDepth(bt->left);
45         int dep_right = BTreeDepth(bt->right);
46         return MAX(dep_left,dep_right)+1;
47     }
48     return 0;
49 }
//BTreeDepth

二叉树的宽度

基本方法:左右子树的宽度相加,于是就得到二叉树的宽度.
66 //get the width of a BST 
67 int BTreeWidth(BTree bt)
68 {
69     if (bt != NULL)
70     {
71         if ((bt->left == bt->right) && (bt->left == NULL))
72             return 1;// bt is a leaf 
73         else
74             return BTreeWidth(bt->left) + BTreeWidth(bt->right);
75     }
76     else
77         return 0;
78 }//BTreeWidth
79 


0 0
原创粉丝点击