二叉树的镜像
题目:操作给定的二叉树,将其变换为源二叉树的镜像。 例如下所示
二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
分析:二叉树镜像,即将所有节点的左右子孩子交换即可,但是要注意几个特例:1、根节点为NULL的情况;2、当前节点没有左右孩子;下面是递归和非递归实现:
1 struct TreeNode { 2 int val; 3 struct TreeNode *left; 4 struct TreeNode *right; 5 TreeNode(int x) : 6 val(x), left(NULL), right(NULL) { 7 } 8 }; 9 10 11 void Mirror(TreeNode *pRoot) { 12 if(pRoot == NULL) 13 return; 14 if(pRoot->left==NULL && pRoot->right==NULL) 15 return; 16 TreeNode* temp = NULL; 17 temp = pRoot->right; 18 pRoot->right = pRoot->left; 19 pRoot->left = temp; 20 if(pRoot->left) 21 Mirror(pRoot->left); 22 if(pRoot->right) 23 Mirror(pRoot->right); 24 }
1 struct TreeNode { 2 int val; 3 struct TreeNode *left; 4 struct TreeNode *right; 5 TreeNode(int x) : 6 val(x), left(NULL), right(NULL) { 7 } 8 }; 9 10 void Mirror(TreeNode *pRoot) { 11 if(pRoot == NULL) 12 return; 13 stack<TreeNode*> stackNode; 14 stackNode.push(pRoot); 15 while(stackNode.size()){ 16 TreeNode* pNode = stackNode.top(); 17 stackNode.pop(); 18 if(pNode->left!=NULL || pNode->right!=NULL){ 19 TreeNode* temp; 20 temp = pNode->right; 21 pNode->right = pNode->left; 22 pNode->left = temp; 23 } 24 if(pNode->right) 25 stackNode.push(pNode->right); 26 if(pNode->left) 27 stackNode.push(pNode->left); 28 } 29 }