题目的要求如上图所示
测试用例(先构造二叉查找树)
void buildBSTreeNode(BSTreeNode* head,int data){ node = (BSTreeNode*)malloc(sizeof(BSTreeNode)); node->data = data; node->m_Left = NULL; node->m_Right = NULL; BSTreeNode* p = head;
while(p){
if(node->data > p->data){
if(!p->m_Right){
p->m_Right = node;
return ;
}
p = p->m_Right;
else
if(node->data < p->data){
if(!p->m_Left){
p->m_Left = node;
return ;
}
p = p->m_Left;
}
else
{
printf("已存在 ");
return ;
}
}
}
int main(){ BSTreeNode* head = (BSTreeNode*)malloc(sizeof(BSTreeNode)); head->m_Left = NULL; head->m_Right = NULL; int data; printf("Enter data(end with 0) "); scanf("%d",&data); head->data = data; while(data){ printf("Enter data(end with 0) "); scanf("%d",&data); if(!data) break; buildBSTree(head, data); } }
释放内存:
void freeBSTree(BSTreeNode* head){ if(head->m_Left) freeBSTree(head->m_Left); if(head->m_Right) freeBSTree(head->m_Right) free(head); }
自己也想不出好的方法,只能是参考别人的
节点:
struct BSTreeNode{ int data; BSTreeNode* m_Left; BSTreeNode* m_Right; };
节点转换:(方法一)
(采用递归的方法,将左子树和右子树以此转化为链表)
BSTreeNode* ConvertNode(BSTreeNode * node, bool isLeft){ //如果是左子树,则返回最大节点;否则,返回最小节点 if(!node) return NULL; BSTreeNode* Left = NULL; BSTreeNode* Right = NULL; if(BSTreeNode->m_Left) Left = ConvertNode(BSTreeNode->m_Left,true); if(Left) Left->m_Right = node; node->m_Left = Left; if(BSTreeNode->m_Right) Right = ConvertNode(BSTreeNode->m_Right,false); if(Right) Right->m_Left = node; node->m_Right = Right; BSTreeNode* temp = node; if(isLeft) while(temp->m_Right) temp = temp->m_Right; else while(temp->m_Left) temp =temp->m_Left; return temp; }
主函数:
#include<stdio.h> int main(){ head = ConvertNode(head,false); //假设head为二叉查找树,则返回的就是最小的节点,再遍历head即可 return 0;
}
节点转换(方法二)
采用中序遍历二叉树
void ConvertNode2(BSTreeNode* node, BSTreeNode*& lastOfList){ BSTreeNode* currentNode = node; if(!node) return ; if(node->m_Left) ConvertNode2(node->m_Left, lastOfList); if(lastOfList) lastOfList->m_Right = currentNode; currentNode->m_Left = lastOfList; lastOfList = currentNode; if(node->m_Right) ConvertNode2(node->m_Right,lastOfList); }
主函数:
int main(){ BSTreeNode* lastOfList = NULL; ConvertNode2(head,lastOfList); //使指针移到首节点 while(head->m_Left) head = head->m_Left; return 0; }