18.二叉树的镜像——剑指offer
题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。(反转二叉树)
1 class Solution { 2 public: 3 //栈的非递归 4 void Mirror(TreeNode *pRoot) { 5 if (pRoot == NULL)return; 6 stack<TreeNode*> st; 7 TreeNode* p = NULL; 8 st.push(pRoot); 9 while (st.size()) 10 { 11 p = st.top(); 12 st.pop(); 13 swap(p->left, p->right); 14 if (p->left)st.push(p->left); 15 if (p->right)st.push(p->right); 16 } 17 } //队列的非递归 18 void Mirror(TreeNode *pRoot) { 19 if (pRoot == NULL)return; 20 queue<TreeNode*> qu; 21 TreeNode* p = NULL; 22 qu.push(pRoot); 23 while (qu.size()) 24 { 25 p = qu.front(); 26 qu.pop(); 27 swap(p->left, p->right); 28 if (p->left)qu.push(p->left); 29 if (p->right)qu.push(p->right); 30 } 31 } 32 //递归 33 void Mirror(TreeNode *pRoot) { 34 if (pRoot == NULL)return; 35 swap(pRoot->left, pRoot->right); 36 Mirror(pRoot->left); 37 Mirror(pRoot->right); 38 } 39 };