设为首页 加入收藏

TOP

二叉树的12大问题(三)
2013-05-03 18:18:08 来源: 作者: 【 】 浏览:107
Tags:问题

 

    //问题10:10.一棵排序二叉树(即二叉搜索树BST),令 f=(最大值+最小值)/2,设计一个算

    //法,找出距离f值最近、大于f值的结点。复杂度如果是O(n2)则不得分。

    int findNearmid(treeNode** root){

    treeNode* ptr = *root;

    int min, max;

    while (ptr != NULL){

    min = ptr->data;

    ptr = ptr->lchild;

    }

    printf("the min is %d\n",min);

    ptr = *root;

    while (ptr != NULL){

    max = ptr->data;

    ptr = ptr->rchild;

    }

    printf("the max is %d\n",max);

    int half = (min + max) 》 1;

    printf("half is %d\n",half);

    ptr = *root;

    while (1){

    if (ptr->data < half){

    ptr = ptr->rchild;

    }

    else

    if (ptr->data > half){

    int result = ptr->data;

    return result;

    }

    else

    {

    return (ptr->rchild)->data;

    }

    }

    }

    //问题12:打印二叉树中的所有路径(与题目5很相似)

    void printPathsRecur(treeNode* node, int path[], int pathLen) {

    if (node == NULL)

    return;

    // append this node to the path array

    path[pathLen] = node->data;

    pathLen++;

    // it's a leaf, so print the path that led to here

    if (node->lchild == NULL && node->rchild == NULL) {

    printArray(path, pathLen);

    } else {

    // otherwise try both subtrees

    printPathsRecur(node->lchild, path, pathLen);

    printPathsRecur(node->rchild, path, pathLen);

    }

    }

    void printPaths(treeNode* node) {

    int path[1000];

    printPathsRecur(node, path, 0);

    }

    //用到的辅助函数:

    /**

    * 求二叉树的深度

    */

    int getDepth(tNode root) {

    if (root == NULL)

    return 0;

    else

    return getDepth(root->lchild) > getLeaf(root->rchild) 1 +

    getDepth(

    root->lchild) : 1 + getDepth(root->rchild);

    //  {

    //      int depthLchild = 1 + getDepth(root->lchild);

    //      int depthRchild = 1 + getDepth(root->rchild);

    //      return depthLchild > depthRchild depthLchild:

    depthRchild;

    //  }

    }

    /**

    * 打印数组

    */

    void printArray(int ints[], int len) {

    int i;

    for (i = 0; i < len; i++) {

    printf("%d ", ints[i]);

    }

    printf("\n");

    }

        

首页 上一页 1 2 3 下一页 尾页 3/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇双向循环链表的实现 下一篇不使用sizeof, 计算int的位..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: