剑指offer 二叉树的镜像
题目:操作给定的二叉树,将其变换为源二叉树的镜像。
如:
二叉树的镜像定义:源二叉树 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 == nullptr) { 14 return; 15 } 16 TreeNode *tmp = pRoot->left; 17 pRoot->left = pRoot->right; 18 pRoot->right = tmp; 19 Mirror(pRoot->left); 20 Mirror(pRoot->right); 21 } 22 };
解法二:栈实现
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) 14 return; 15 stack<TreeNode*> st; 16 st.push(pRoot); 17 while (!st.empty()) { 18 TreeNode* top = st.top(), *tmp; 19 st.pop(); 20 tmp = top->left; 21 top->left = top->right; 22 top->right = tmp; 23 if (top->left != NULL) 24 st.push(top->left); 25 if (top->right != NULL) 26 st.push(top->right); 27 } 28 } 29 };
越努力,越幸运