rt 直接贴代码
#include <iostream>
#include <string>
using namespace std;
typedef struct Node{
int value;
Node *left;
Node *right;
} Node;
void visitRight(Node *root){
Node *cur = root;
while(cur){
cout<<cur->value<<" ";
cur = cur->right;
}
}
void visitLeft(Node *root){
Node *cur = root;
while(cur){
cout<<cur->value<<" ";
cur = cur->left;
}
}
//
void trival(Node *root, Node *&head, Node *&tail){
if(root->left==NULL && root->right==NULL){
head=tail=root;
return;
}
Node *tl, *tr;
if(root->left){
trival(root->left, tl, tr);
head=tl;
root->left=tr;
tr->right=root;
}
else{
head = root;
}
if(root->right){
trival(root->right, tl, tr);
tail=tr;
root->right=tl;
tl->left=root;
}
else{
tail=root;
}
}
int main(){
Node *head, *tail;
/
Node r, l1, r1, l2, l3, l4, r4, r5;
r.value=1; l1.value=2; r1.value=3; l2.value=4; l3.value=5; l4.value=6; r4.value=7; r5.value=8;
r.left=&l1; r.right=&r1;
l1.left=&l2; l1.right=NULL;
l2.left=l2.right=NULL;
r1.left=&l3; r1.right=NULL;
l3.left=&l4; l3.right=&r4;
l4.left=l4.right=NULL;
r4.left=NULL; r4.right=&r5;
r5.left=r5.right=NULL;
//
// r 1
// / \ / \
// l1 r1 2 3
// / / / /
// l2 l3 4 5
// / \ / \
// l4 r4 6 7
// \ \
// r5 8
/
trival(&r, head, tail);
visitRight(head);
cout<<endl;
visitLeft(tail);
cout<<endl;
return 0;
}