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

来源:互联网 发布:淘宝主图素材价格 编辑:程序博客网 时间:2024/04/29 14:09

// 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;
}

 

原创粉丝点击