LeetCode-二叉树的镜像
二叉树的镜像
二叉树的镜像
- 给定一个二叉树,输出二叉树的镜像。
- 只需要使用一个简单的递归,分别对左右子树反转后再对当前结点进行反转。
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 4
// / \
// 2 7
// / \ / \
// 1 3 6 9
class Solution {
public:
void reverse(TreeNode* node){
if(node->left){
reverse(node->left);
}
if(node->right){
reverse(node->right);
}
TreeNode* temp=node->left;
node->left=node->right;
node->right=temp;
}
TreeNode* mirrorTree(TreeNode* root) {
if(root)//root不为null
reverse(root);
return root;
}
};
int main(){
TreeNode* t1=new TreeNode(1);
TreeNode* t2=new TreeNode(2);
TreeNode* t3=new TreeNode(3);
TreeNode* t4=new TreeNode(4);
TreeNode* t6=new TreeNode(6);
TreeNode* t7=new TreeNode(7);
TreeNode* t9=new TreeNode(9);
t7->left=t6;t7->right=t9;
t2->left=t1;t2->right=t3;
t4->left=t2;t4->right=t7;
Solution solution;
TreeNode* root=solution.mirrorTree(t4);
cout<<root->left->val<<" "<<root->right->val<<endl;
system("pause");
return 0;
}
Either Excellent or Rusty