题解 | #二叉树的镜像#
二叉树的镜像
http://www.nowcoder.com/practice/a9d0ecbacef9410ca97463e4a5c83be7
C语言
思路:从创建二叉树的方法入手,创建二叉树的时候使用递归调用的方法给根结点、左子树、右子树分别赋值。题目要求镜像,实际上就是将每一层的左右子树互换,因此考虑在赋值的时候将赋值过程进行交换。重新定义一个函数exchange,用于交换指针指向,在创建二叉树的过程中进行左右子树的互换。
代码如下:
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return TreeNode类
*/
void exchange(struct TreeNode*pRoot)
{
struct TreeNode*T;
T=(pRoot->left);
(pRoot->left)=(pRoot->right);
pRoot->right=T;
}
struct TreeNode* Mirror(struct TreeNode* pRoot ) {
// write code here
if(pRoot==NULL)
{
return NULL;
}
else
{
exchange(pRoot);
Mirror(pRoot->left);
Mirror(pRoot->right);
}
return pRoot;
}牛客刷题记录 文章被收录于专栏
记录自己的刷题记录,刷过的题的解法
查看13道真题和解析
