1.二叉树镜像是指左右对换一个二叉树
1 / \ 2 4 / / 3 5
变成
1 / \ 4 2 \ \ 5 3
递归交换非叶子节点左右子树即可
2.代码
#include<stdio.h> #include<stack> struct BinaryTree { int value; BinaryTree* left; BinaryTree* right; }; void mirrorTreeDFS(BinaryTree* root) { if(root==NULL || (root->left==NULL && root->right==NULL)) return; BinaryTree *tmp = root->left; root->left = root->right; root->right = tmp; if(root->left) mirrorTreeDFS(root->left); if(root->right) mirrorTreeDFS(root->right); } void mirrorTree(BinaryTree* root) { if(root==NULL || (root->left==NULL && root->right==NULL)) return; std::stack nodeStack; nodeStack.push(root); while(nodeStack.size() > 0) { BinaryTree* cur = nodeStack.top(); nodeStack.pop(); BinaryTree* tmp = cur->left; cur->left = cur->right; cur->right = tmp; if(cur->left) nodeStack.push(cur->left); if(cur->right) nodeStack.push(cur->right); } }