int bstree_predecessor( bstree_t *tree_in, long idx_in, long *idx_out ) { long p,q; if( tree_in->start[idx_in].left != -1 ) bstree_maximum( tree_in, tree_in->start[idx_in].left, idx_out ); else { q = idx_in; p = tree_in->start[q].parent; while( p != -1 && q == tree_in->start[p].left ) { q = p; p = tree_in->start[p].parent; } *idx_out = p; } return 0; }
/* * 找结点(x)的前驱结点。即,查找"二叉树中数据值小于该结点"的"最大结点"。 */ Node* bstree_predecessor(Node *x) { // 如果x存在左孩子,则"x的前驱结点"为 "以其左孩子为根的子树的最大结点"。 if (x->left != NULL) return bstree_maximum(x->left); // 如果x没有左孩子。则x有以下两种可能: // (01) x是"一个右孩子",则"x的前驱结点"为 "它的父结点"。 // (01) x是"一个左孩子",则查找"x的最低的父结点,并且该父结点要具有右孩子",找到的这个"最低的父结点"就是"x的前驱结点"。 Node* y = x->parent; while ((y!=NULL) && (x==y->left)) { x = y; y = y->parent; } return y; }
void main() { int i, ilen; BSTree root=NULL; printf("== 依次添加: "); ilen = TBL_SIZE(arr); for(i=0; i<ilen; i++) { printf("%d ", arr[i]); root = insert_bstree(root, arr[i]); } printf("\n== 前序遍历: "); preorder_bstree(root); printf("\n== 中序遍历: "); inorder_bstree(root); printf("\n== 后序遍历: "); postorder_bstree(root); printf("\n"); printf("== 最小值: %d\n", bstree_minimum(root)->key); printf("== 最大值: %d\n", bstree_maximum(root)->key); printf("== 树的详细信息: \n"); print_bstree(root, root->key, 0); printf("\n== 删除根节点: %d", arr[3]); root = delete_bstree(root, arr[3]); printf("\n== 中序遍历: "); inorder_bstree(root); printf("\n"); // 销毁二叉树 destroy_bstree(root); }