Skip to the content.

Ex27 二叉树的镜像

题目描述

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

例如输入: ​ 4 /
2 7 / \ /
1 3 6 9 镜像输出: ​ 4 /
7 2 / \ /
9 6 3 1

解题思路

这个主要用的就是在左子树和右子树上递归地进行,唯一需要注意的是要先保存左子树。

代码

struct TreeNode *
mirrorTree (struct TreeNode *root)
{
  if (!root)
    return NULL;
  struct TreeNode *tmp_node = root->left;
  root->left = mirrorTree (root->right);
  root->right = mirrorTree (tmp_node);
  return root;
}

结果

执行结果:通过

执行用时:0 ms, 在所有 C 提交中击败了100.00%的用户

内存消耗:5.7 MB, 在所有 C 提交中击败了27.52%的用户