void addNode(NODE* pNode){
enum pflag flag;
if(root==NULL){
root=pNode;
return;
}
NODE* temp=root;
NODE* proot=null;
while(true){
if(temp->value>pNode->value){
if(temp->left==null){
temp->left=pNode;
return;
}else{
proot=temp;
temp=temp->left;
flag=l;
}
}else if(temp->value<pNode->value){
if(temp->right==null){
temp->right=pNode;
return;
}else{
proot=temp;
temp=temp->right;
flag=r;
}
}else if(temp->value==pNode->value){//节点相同则替换 flag 标记左右子节点
if(flag==l){
NODE * left=proot->left->left;
NODE* right=proot->left->right;
pNode->left=left;
pNode->right=right;
free(proot->left);
proot->left=pNode;
}else if(flag==r){
NODE * left=proot->right->left;
NODE* right=proot->right->right;
pNode->left=left;
pNode->right=right;
free(proot->right);
proot->right=pNode;
}
n++;
break;
}
}
}
/**
*
*
* 查看节点的高度
*
*/
int height(NODE * pnode){//查看节点的高度
int lheight=0;
int rheight=0;
if(pnode==null)
return 0;
if(pnode->left!=null)
lheight= height(pnode->left);
if(pnode->right!=null)
rheight= height(pnode->right);
return (lheight>rheight? lheight:rheight)+1;
}
static int num=0;
void MidShowBtree(NODE * root){//中序迭代遍历树
if(root==null){
return;
}
NODE * temp=root;
if(temp->left!=null){
MidShowBtree(temp->left);
}
printf("%d ",temp->value);
if(temp->right!=null){
MidShowBtree(temp->right);
}
}
int findleftmax(NODE* pnode){
NODE* temp=pnode;
if(temp!=null){
temp=temp->left;
if(temp->right==null){
return temp->value;
}
while(temp!=null){
temp=temp->right;
if(temp->right==null){
return temp->value;
}
}
}
}
int findrightmin(NODE* pnode){
NODE* temp=pnode;
if(temp!=null){
temp=temp->right;
if(temp->left==null){
return temp->value;
}
while(temp!=null){
temp=temp->left;
if(temp->left==null){
return temp->value;
}
}
}
}
NODE* pushstack(NODE* node){
if(node==null){
return null;
}
NODE* temp=node;
while(temp->left!=null){//左子树压栈
push(temp);
temp=temp->left;
}
printf("%d ",temp->value);
return temp;
}
void StackMidShow(NODE* proot){//用栈中序遍历
if(proot==null){
return ;
}
NODE* temp= pushstack(proot);
while(temp){
if(temp->right!=null){
temp= temp->right;
temp= pushstack(temp);
}else if(size()>0){
temp=pop();
printf("%d ",temp->value);
}else if(size()==0){
break;
}
}
}
NODE* GoLeft(NODE* root){
if (root == NULL)
{
printf("参数不可以为空!\n");
return NULL;
}
while (root->left){
//入栈
push(root);
root = root->left;
}
return root;
}
//树的非递归遍历
void TreeErgodic(NODE* root){
if (root==NULL)
{
return;
}
NODE* t = GoLeft(root);
/*
此时t不可能为NULL,因为root不为NULL
*/
printf("%d ", t->value);
while (t){
//如果结点有右子树,重复步骤1;
if (t->right!=NULL)
{
t = GoLeft(t->right);
printf("%d ", t->value);
}
//如果结点没有右子树(结点访问完毕),回退,让栈顶元素出栈,访问栈顶元素,并访问右子树,重复步骤1
else if (size()>0){
t =pop();
printf("%d ", t->value);
}
//如果栈为空,表示遍历结束。
else{
t = NULL;
}
}
}