非递归交换二叉树左右子树:BinaryTree:Exchange the left child and the right child without recursive method

// BTree.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
#include "stack"
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)
{
 stack<Node*> s;
 s.push(root);
 while(!s.empty())
 {
  Node* p=s.top();
  s.pop();
  if(p->lch||p->rch)
  {
   Node* temp=p->lch;
   p->lch=p->rch;
   p->rch=temp;
  }
  if(p->lch)
   s.push(p->lch);
  if(p->rch)
   s.push(p->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);
SwapChild(head);
InorderTree(head);
cin.get();
 return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值