代码自己敲的,中间建树的时候遇到了麻烦,以前是先申请空间给根节点,这样的话根节点就需要单独处理。
突发奇想用了下双重指针,对双重指针的作用和用法有了更好的理解。
用递归解法做这个问题不难,主要熟悉了一下建树,打印树的代码。
中间有调试代码,就不改了,方便看执行过程。
#include<stdio.h> #include<stdlib.h> #define DEBUG(i) printf("Here " #i " is OK\n"); typedef struct BSTreeNode { int m_nValue; struct BSTreeNode *m_pLeft; struct BSTreeNode *m_pRight; }BSTreeNode; //==================================================================== void iniTree(struct BSTreeNode ** mytree, int data); void printTree(struct BSTreeNode * mytree); void translate(struct BSTreeNode * mytree); //==================================================================== int main() { struct BSTreeNode * mytree = NULL; int num, temp, i; printf("Please input how many numbers in your tree\n"); scanf("%d", &num); for(i = 0; i < num; i++) { DEBUG(1); scanf("%d", &temp); iniTree(&mytree, temp); } translate(mytree); printTree(mytree); DEBUG(0); printf("Congratulations!\n"); return 0; } void iniTree(struct BSTreeNode ** mytree, int data) { DEBUG(2); if(*mytree == NULL) { *mytree = (struct BSTreeNode * )malloc(sizeof(BSTreeNode)); //here change the pointer to an addr, so ** is needed (*mytree)->m_nValue = data; (*mytree)->m_pLeft = NULL; (*mytree)->m_pRight = NULL; return; } else if((*mytree)->m_nValue >= data) iniTree(&((*mytree)->m_pLeft), data); else iniTree(&((*mytree)->m_pRight), data); } void printTree(struct BSTreeNode * mytree) { DEBUG(3); if(mytree != NULL) { printf("%d\n", mytree->m_nValue); if(mytree->m_pLeft != NULL) printTree(mytree->m_pLeft); if(mytree->m_pRight != NULL) printTree(mytree->m_pRight); } } void translate(struct BSTreeNode * mytree) { if(!mytree) return ; if(mytree->m_pLeft) translate(mytree->m_pLeft); if(mytree->m_pRight) translate(mytree->m_pRight); struct BSTreeNode * temp; temp = mytree->m_pLeft; mytree->m_pLeft = mytree->m_pRight; mytree->m_pRight = temp; }