第十二章:二叉查找树(1)
二叉查找树的基本操作
#include <iostream> #include <stack> using namespace std; stack<TreeNode *> s; typedef int Data; struct TreeNode{ Data data; TreeNode *parent; TreeNode *left; TreeNode *right; }; //创建一颗查找二叉树 TreeNode *Create_Tree(int num){ TreeNode *p=(TreeNode *)malloc(sizeof(TreeNode)); TreeNode *root,*child,*parent; child=root=p; p->parent=p->left=p->right=NULL; cin>>root->data; int i=0; while (++i<num){ TreeNode *p=(TreeNode *)malloc(sizeof(TreeNode)); p->parent=p->left=p->right=NULL; cin>>p->data; child=root; while (child){ parent=child; if (p->data>child->data){ child=child->right; }else{ child=child->left; } } if (p->data>parent->data){ parent->right=p; p->parent=parent; }else{ parent->left=p; p->parent=parent; } } return root; } TreeNode *Tree_Search(TreeNode *t,int key){ while (t&&t->data!=key){ if (t->data>key){ t=t->left; }else{ t=t->right; } } return t; } TreeNode *Minimum(TreeNode *t){ while (t->left){ t=t->left; } return t; } TreeNode *Maximum(TreeNode *t){ while (t->right){ t=t->right; } return t; } TreeNode *Tree_Successor(TreeNode *t){ if (t->right){ return Minimum(t->right); }else{ while (t->parent&&t->parent->right==t){ t=t->parent; } return t->parent; } } TreeNode *Tree_Predecessor(TreeNode *t){ if (t->left){ t=t->left; while (t->right){ t=t->right; } return t; }else if (t->parent){ return t->parent; } }