二叉树的镜像

题目描述

操作给定的二叉树,将其变换为源二叉树的镜像。

输入描述:

二叉树的镜像定义:源二叉树 
    	    8
    	   /  \
    	  6   10
    	 / \  / \
    	5  7 9 11
    	镜像二叉树
    	    8
    	   /  \
    	  10   6
    	 / \  / \
    	11 9 7  5

 1 /*
 2 struct TreeNode {
 3     int val;
 4     struct TreeNode *left;
 5     struct TreeNode *right;
 6     TreeNode(int x) :
 7             val(x), left(NULL), right(NULL) {
 8     }
 9 };*/
10 class Solution {
11 public:
12     void Mirror(TreeNode *pRoot) {
13         TreeNode* left,*right;
14         if(pRoot==NULL) return ;
15         left=pRoot->left,right=pRoot->right;
16         pRoot->left=right;
17         pRoot->right=left;
18         Mirror(pRoot->left);
19         Mirror(pRoot->right);
20     }
21 };

下面是非递归实现

 1 /*
 2 struct TreeNode {
 3     int val;
 4     struct TreeNode *left;
 5     struct TreeNode *right;
 6     TreeNode(int x) :
 7             val(x), left(NULL), right(NULL) {
 8     }
 9 };*/
10 class Solution {
11 public:
12     void Mirror(TreeNode *pRoot) {
13         if(!pRoot) return;
14         stack<TreeNode*> s;
15         s.push(pRoot);
16         while(s.size()){
17             TreeNode* tmp=s.top();
18             s.pop();
19             if(tmp->left||tmp->right){
20                 TreeNode* t=tmp->left;
21                 tmp->left=tmp->right;
22                 tmp->right=t;
23             }
24             if(tmp->left){
25                 s.push(tmp->left);
26             }
27             if(tmp->right){
28                 s.push(tmp->right);
29             }
30         }
31     }
32 };

 

posted on 2017-10-26 10:24  wsw_seu  阅读(147)  评论(0编辑  收藏  举报

导航