您的位置:首页 > 其它

递归交换二叉树左右子树:BinaryTree:Exchange the left child and right child of a binary tree

2009-12-05 11:46 633 查看
// BTree.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
using namespace std;

typedef struct _node
{
int data;
struct _node* rch;
struct _node* lch;
}Node;

Node* InsertNode(Node* n,int d)
{
if(n)
{
if(d>n->data)
n->rch=InsertNode(n->rch,d);
else n->lch=InsertNode(n->lch,d);
}
else
{
n=(Node*)malloc(sizeof(Node));
n->data=d;
n->lch=NULL;
n->rch=NULL;
}
return n;
}
void CreateTree(Node* root,int arr[],int len)
{
for(int i=0;i<len;i++)
{
InsertNode(root,arr[i]);
}

}

void SwapChild(Node* root)
{
if(root)
{
if(root->lch!=NULL||root->rch!=NULL)

{
Node* temp;
temp=root->lch;
root->lch=root->rch;
root->rch=temp;
SwapChild(root->lch);
SwapChild(root->rch);
}
}
}

void InorderTree(Node* root)
{
if(root)
{
InorderTree(root->lch);
cout<<root->data<<" ";
InorderTree(root->rch);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[]={12,34,1,78,54,89};
Node* head=(Node*)malloc(sizeof(Node));
head->data=0;
head->lch=NULL;
head->rch=NULL;
CreateTree(head,a,6);
InorderTree(head);
cin.get();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐