剑指offer之面试题19——二叉树的镜像

题目:

题目:请完成一个函数,输入一个二叉树,该函数输出它的镜像。

代码:


TreeNode* mirror(TreeNode* r) {
	if (!r)return NULL;
	if (!r->left) {
		r->left = mirror(r->right);
	}
	if (!r->right) {
		r->right = mirror(r->left);
	}

	TreeNode* t = new TreeNode(0);
	t->left = mirror(r->right);
	r->right = mirror(r->left);
	r->left = t->left;
	return r;
}
int main() {
	TreeNode* t1 = new TreeNode(1);
	TreeNode* t2 = new TreeNode(2);
	TreeNode* t3 = new TreeNode(3);
	TreeNode* t4 = new TreeNode(4);
	TreeNode* t5 = new TreeNode(5);
	TreeNode* t6 = new TreeNode(6);
	TreeNode* t7 = new TreeNode(7);
	t1->left = t2;
	t1->right = t3;
	t2->left = t4;
	t2->right = t5;
	t3->left = t6;
	t3->right = t7;

	TreeNode* res = mirror(t1);
	
	return 0;
}

 

你可能感兴趣的:(leetcode和机试题)