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

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define LEAF -1

typedef 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;   
}


你可能感兴趣的:(数据结构,struct,null,System,include)