二叉搜索树(BST)插入数据后结构异常,求助排查原因
二叉搜索树插入后结构异常的原因排查
问题背景
依次向实现的二叉搜索树中插入A、B、C、D、E、F、G后,实际生成右斜单链结构,与预期的平衡树结构不符。
实现代码
struct BSTreeNode { struct BSTreeNode *leftchild; AnsiString data; struct BSTreeNode *rightchild; }; struct BSTreeNode * root; String tree = ""; struct BSTreeNode * newNode(AnsiString x) { struct BSTreeNode * node = new struct BSTreeNode; node->data = x; node->leftchild = NULL; node->rightchild = NULL; return node; } struct BSTreeNode * insertBSTree(struct BSTreeNode * node , AnsiString x) { if(node == NULL) return newNode(x); if(x < node->data) node->leftchild = insertBSTree(node->leftchild, x); else node->rightchild = insertBSTree(node->rightchild, x); return node; } void printBSTree(struct BSTreeNode * node) { if(node != NULL) { printBSTree(node->leftchild); tree += node->data+"_"; printBSTree(node->rightchild); } } //--- insert button --- void __fastcall TForm1::Button1Click(TObject *Sender) { AnsiString data; data = Edit1->Text; root = insertBSTree(root, data); tree = ""; printBSTree(root); Memo1->Lines->Add(tree); }
结构对比
预期结构(注:结构中出现的H、J与插入序列A-G不符,应为描述笔误)
A / \ B C / \ / \ H J D E / \ F G
实际结构
A \ B \ C \ D \ E \ F \ G
原因分析
- 插入逻辑的核心依赖:
insertBSTree函数通过x < node->data判断节点插入方向——小于当前节点数据则插左子树,否则插右子树。 - 字符串比较结果:插入的序列是严格升序的
A→B→C→D→E→F→G,每个后续字符的ASCII值均大于前一个(如A的ASCII码为65,B为66,依此类推)。使用AnsiString的默认小于运算符时,所有后续插入的字符都会判定为大于当前节点数据,因此全部被插入到右子树。 - 普通BST的固有特性:当插入严格有序(升序或降序)的序列时,普通二叉搜索树会自然退化成单链表结构,这是此类树的特性,并非代码逻辑错误——若要生成平衡结构,需实现自平衡二叉搜索树(如AVL树、红黑树)。
内容的提问来源于stack exchange,提问作者Cat Ball
相关产品推荐
相关产品推荐

