方法:递归:
根据二叉树镜像的定义,考虑提柜遍历二叉树,交换每个节点,即可生成二叉树的镜像。
递归解析:
1、终止条件:当节点root为空时(即越过叶节点)则返回null:
2、递推工作:
1.初始化节点node,用于存储镜像的二叉树的节点
2.开启递归node->left=mirrorTree(root->right) ,将返回值作为镜像二叉树的左节点
3.开启递归node->right=mirrorTree(root->left),将返回值作为镜像二叉树的右节点。
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * struct TreeNode *left; 6 * struct TreeNode *right; 7 * }; 8 */ 9 10 11 struct TreeNode* mirrorTree(struct TreeNode* root){ 12 if(root==0) return NULL; 13 struct TreeNode* Node=(struct TreeNode*)malloc(sizeof(struct TreeNode)); 14 Node->val=root->val; 15 Node->left=mirrorTree(root->right); 16 Node->right=mirrorTree(root->left); 17 return Node; 18 }
原文:https://www.cnblogs.com/sbb-first-blog/p/13289730.html