【学习点滴-数据结构-二叉树】二叉树中找大于等于(min+max)/2的节点

来源:互联网 发布:淘宝怎么搞 编辑:程序博客网 时间:2024/06/14 10:15
#include <stdio.h>#include <stdlib.h>#include <malloc.h>#define LEAF -1typedef struct BTreeNode{     BTreeNode* lchild;     BTreeNode* rchild;     int value;               }BTreenode,*Btree;BTreenode* createTree(){     BTreeNode* T;     int t;       scanf("%d",&t);     if(t==LEAF){          T = NULL;     }else{          T = (BTreeNode *) malloc(sizeof(BTreeNode));          T->value = t;          T->lchild = createTree();          T->rchild = createTree();         }     return T;}int f(BTreeNode * maxNode,BTreeNode * minNode){    return (maxNode->value + minNode->value)/2;}//找大于等于key的最近节点 BTreeNode * findTheNode(BTreeNode* root,int key){    if(root == NULL){        return NULL;            }    //分情况讨论1:大于根节点的值。从右子树中找     if(key == root->value){        return root;           }    else if(key > root->value){         if(root->rchild ==NULL){              return root;                    }else{              BTreeNode * node =  findTheNode(root->rchild,key);              return node->value >= key?node : root;          }      }    // 分情况讨论2:小于根节点的值。从左子树中找     else{         if(root->lchild == NULL){              return root;                         }         BTreeNode * node = findTheNode(root->lchild,key);         return node->value >= key? node:root;     }  }BTreeNode * getMinNode(BTreeNode * root){    BTreeNode * min = root;    while(min->lchild != NULL){         min = min->lchild;       }    return min;      } BTreeNode * getMaxNode(BTreeNode * root){    BTreeNode * max = root;    while(max->rchild != NULL){        max= max->rchild;    }     return max;    } main(){    BTreeNode * root,* min,* max,*result;    int key;    root = createTree();    min =  getMinNode(root);    max =  getMaxNode(root);    key =  f(min,max);    printf("min:%d ,max:%d,f:%d\n",min->value,max->value,key);    result = findTheNode(root,key);    printf("result :%d\n",result->value);    system("pause");         return 0;   }


原创粉丝点击