设树B是一颗采用链式结构存储的二叉树,编写一个把树B种所有节点的左、右子树进行交换的函数。
#include <iostream>
#include <stack>
typedef struct treenode{char data;struct treenode *left;struct treenode *right;
}treenode,*ptreenode;ptreenode buytreenode(char x)
{ptreenode n=(ptreenode) malloc(sizeof (treenode));n->data=x;n->left= nullptr,n->right= nullptr;return n;
}
ptreenode build_tree()
{ptreenode root= buytreenode('A');root->left= buytreenode('B');root->right= buytreenode('C');root->left->left= buytreenode('D');root->left->right= buytreenode('E');return root;
}ptreenode reversetree(ptreenode root)
{if(root== nullptr) return root;ptreenode tmp=root->left;root->left= reversetree(root->right);root->right= reversetree(tmp);
}
int main() {ptreenode root=build_tree();printf("%3c",root->data);printf("%3c",root->left->data);printf("%3c",root->right->data);printf("%3c",root->left->left->data);printf("%3c",root->left->right->data);puts("");ptreenode newroot= reversetree(root);printf("%3c",newroot->data);printf("%3c",newroot->left->data);printf("%3c",newroot->right->data);printf("%3c",newroot->right->left->data);printf("%3c",newroot->right->right->data);return 0;
}