二叉树的镜像(剑指offer+递归)抽象有关问题具体化
二叉树的镜像(剑指offer+递归)抽象问题具体化
二叉树的镜像
- 参与人数:1868时间限制:1秒空间限制:32768K
- 通过比例:30.59%
- 最佳记录:0 ms|0K(来自 一半天才,一半蠢材)
题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \ 11 9 7 5
题目链接:http://www.nowcoder.com/practice/564f4c26aa584921bc75623e48ca3011?rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
当遇到比较抽象的名词时,我们可以画图来找规律!
思路:每次根节点不动,交换他的左右结点,然后递归他的左右结点;其实也就是把建树的规则倒过来而已;
测试数据:1、空树,2、只有根节点,3、普通样例,4、二叉树只有左子树或只有右子树
struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; class Solution { public: void Mirror(TreeNode *pRoot) { if(!pRoot) return ;//空树 if(!pRoot->left && !pRoot->right) return ;//叶子结点 TreeNode *tree=new TreeNode(NULL); tree=pRoot->left; pRoot->left=pRoot->right; pRoot->right=tree; if(pRoot->left) Mirror(pRoot->left); if(pRoot->right) Mirror(pRoot->right); } };
版权声明:本文为博主原创文章,未经博主允许不得转载。