输入一颗二元查找树,将该树转换为它的镜像,
即在转换后的二元查找树中,左子树的结点都大于右子树的结点。
用递归和循环两种方法完成树的镜像转换。
例如输入:
8
/ \
6 10
/\ /\
5 7 9 11
输出:
8
/ \
10 6
/\ /\
11 9 7 5
非递归版本采用栈来实现:
#include <stdio.h> #include <stack> using namespace std; struct Node{ int data; Node* left; Node* right; Node(){} Node(int d){ data = d; left = NULL; right = NULL; } }; Node* mirror(Node* root){ if(root==NULL) return NULL; Node* temp = root->left; root->left = mirror(root->right); root->right = mirror(temp); return root; } Node* mirror_norecursion(Node* root){ stack<Node* > mys; mys.push(root); while(!mys.empty()){ Node* curr = mys.top(); Node* temp = curr->left; curr->left = curr->right; curr->right = temp; mys.pop(); if(curr->left!=NULL) mys.push(curr->left); if(curr->right!=NULL) mys.push(curr->right); } return root; } void preorder(Node* root){ if(root==NULL) return; printf("%d ",root->data); preorder(root->left); preorder(root->right); } int main(){ Node* root = new Node(12); Node* n1 = new Node(1); Node* n2 = new Node(2); Node* n3 = new Node(3); root->left = n1; root->right = n2; n1->left = n3; preorder(root); puts(""); preorder(mirror(root)); puts(""); preorder(mirror_norecursion(root)); puts(""); return 0; }