描述: 操作给定的二叉树,将其变换为源二叉树的镜像。
二叉树的镜像示例:
源二叉树 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) 14 return; 15 if(!pRoot->left && !pRoot->right) 16 return; 17 TreeNode *pTemp = pRoot->left; 18 pRoot->left = pRoot->right; 19 pRoot->right = pTemp; 20 Mirror(pRoot->left); 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) 14 return; 15 stack<TreeNode*> pStack; 16 pStack.push(pRoot); 17 while(!pStack.empty()) 18 { 19 TreeNode *cur = pStack.top(); 20 pStack.pop(); 21 if(cur->left || cur->right) 22 { 23 TreeNode *temp = cur->left; 24 cur->left = cur->right; 25 cur->right = temp; 26 } 27 if(cur->left) 28 pStack.push(cur->left); 29 if(cur->right) 30 pStack.push(cur->right); 31 } 32 } 33 };