获取二叉搜索树叶子节点的深度

#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#define SIZE 100
int depth=0;
int num=0;
int d[100];

typedef struct _tree_node
{
     int m_nValue;
     struct _tree_node *m_pLeft;
     struct _tree_node *m_pRight;
}TreeNode;


void getNodePath(TreeNode *pHead)
{
     if(pHead==NULL)
     return;
     
     depth++;
     getNodePath(pHead->m_pLeft);
     if(pHead->m_pLeft==NULL&&pHead->m_pRight==NULL)
     {
         d[num++]=depth;
     }
     getNodePath(pHead->m_pRight);
     depth--;
}



void initTree(TreeNode **ppHead,int value)
{
     if(ppHead==NULL)
     return;
     
     if(*ppHead==NULL)
     {
         *ppHead=(TreeNode *)malloc(sizeof(TreeNode));
         assert(*ppHead!=NULL);
         (*ppHead)->m_nValue=value;
         (*ppHead)->m_pLeft=NULL;
         (*ppHead)->m_pRight=NULL;
     }
     else if(value<(*ppHead)->m_nValue)
     {
          initTree(&(*ppHead)->m_pLeft,value);
     }
     else
     {
          initTree(&(*ppHead)->m_pRight,value);
     }
     
}

/*void printTree(TreeNode *pNode)
{
     if(pNode==NULL)
     return;
     printTree(pNode->m_pLeft);
     //printf("%d ",pNode->m_nValue);
     printTree(pNode->m_pRight);
     printf("%d ",pNode->m_nValue);
}*/

int main()
{
    TreeNode *pHead=NULL;
    int value;
    while(scanf("%d",&value)&&value!=-1)
    {
         initTree(&pHead,value);
    }
    
   // TreeNode *pNode=pHead;
    //printTree(pNode);
    
    TreeNode *pNode=pHead;
    getNodePath(pNode);
    
    int k=0;
    for(;k<100;k++)
    {
        printf("%d ",d[k]);
    }
    
    
    
    system("pause");
    return 0;
}

posted @ 2013-09-16 13:03  liguigen  阅读(327)  评论(0编辑  收藏  举报