【剑指Offer27-二叉树的镜像(C++附带测试)】

在这里插入图片描述
这题有点意思,因为想明白一点就好了:

为了得到镜像的树,实际上就是对每一个节点交换左右子树。

那么我们为了方便递归,从底层开始,因为这样才能得到一个正确的交换结果。

#include<iostream>
#include<vector>
#include<algorithm>

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) {}
 * };
 */
struct TreeNode{
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x):val(x),left(NULL),right(NULL){}
};


class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
    	if(root==nullptr){
    		return nullptr;
		}
        root->left = mirrorTree(root->left);
        root->right = mirrorTree(root->right);
        
        TreeNode* temp = root->left;
        root->left = root->right;
        root->right = temp;
        
        return root;
    }
};

TreeNode* create(vector<int> a,int i){
	if(a[i]==-1){
		return nullptr;
	}
	
	TreeNode* root = new TreeNode(a[i]);
	int left = i*2+1;
	int right = i*2+2;
	
	if(left>a.size()-1){
		root->left = nullptr;
	}else{
		root->left = create(a,left);
	}
	
	if(right>a.size()-1){
		root->right = nullptr;
	}else{
		root->right = create(a,right);
	}
	
	return root;
} 

void preorder(TreeNode* root){
	if(root==nullptr){
		return;
	}
	cout<<root->val<<" ";
	preorder(root->left);
	preorder(root->right);
}



int main(){
	vector<int> Tree1{4,2,7,1,3,6,9};
	TreeNode* Treehead1 = create(Tree1,0);
	preorder(Treehead1);
	cout<<endl;
	Solution solution;
	Treehead1 = solution.mirrorTree(Treehead1);
	preorder(Treehead1);
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值