标签:
二叉树的镜像定义:源二叉树 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 if(pRoot==NULL|| (pRoot->left==NULL && pRoot->right==NULL)) 14 return; 15 TreeNode * node=pRoot->left; 16 pRoot->left=pRoot->right; 17 pRoot->right=node; 18 if(pRoot->left) 19 Mirror(pRoot->left); 20 if(pRoot->right) 21 Mirror(pRoot->right); 22 } 23 };
方法二:迭代实现
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==NULL|| (pRoot->left==NULL && pRoot->right==NULL)) 14 return; 15 stack<TreeNode*> stackNode; 16 stackNode.push(pRoot); 17 while(stackNode.size()!=0){ 18 TreeNode* treeNode=stackNode.top(); 19 stackNode.pop(); 20 if(treeNode->left!=NULL ||treeNode->right!=NULL){ 21 TreeNode *temp=treeNode->left; 22 treeNode->left=treeNode->right; 23 treeNode->right=temp; 24 } 25 if(treeNode->left) 26 stackNode.push(treeNode->left); 27 if(treeNode->right) 28 stackNode.push(treeNode->right); 29 } 30 } 31 };
标签:
原文地址:http://www.cnblogs.com/lou424/p/5023859.html