程序中包含了递归方法 和循环方法
#include <iostream> #include <queue> using namespace std; struct tree { int value; tree *left; tree *right; }; tree *create() { int n; cin>>n; if (n == 0) { return NULL; } else { tree *root = new tree; root->value = n; root->left = create(); root->right = create(); return root; } } void pre(tree *root) { if (root == NULL) { return; } else { cout<<root->value<<" "; pre(root->left); pre(root->right); } } void mirror_digui(tree *root) { if (root == NULL || (root->left==NULL && root->right==NULL)) { return ; } tree *temp = root->left; root->left = root->right; root->right = temp; if (root->left != NULL) { mirror_digui(root->left); } if (root->right != NULL) { mirror_digui(root->right); } } void mirror_xunhuan(tree *root) { if (root == NULL || (root->left==NULL && root->right==NULL)) { return ; } queue<tree *> q; q.push(root); while(!q.empty()) { tree *newroot = q.front(); q.pop(); tree *temp = newroot->left; newroot->left = newroot->right; newroot->right = temp; if (newroot->left!=NULL) { q.push(newroot->left); } if (newroot->right!=NULL) { q.push(newroot->right); } } } int main() { tree *root = create(); pre(root); cout<<endl; mirror_xunhuan(root); pre(root); return 0; }
用循环的方法实现二叉树的镜像
时间: 2024-12-29 05:24:54