二叉树镜像
1 #include <iostream> 2 #include <vector> 3 #include <queue> 4 using namespace std; 5 struct Treenode 6 { 7 int val; 8 Treenode* left; 9 Treenode* right; 10 Treenode(int _val):val(_val),left(nullptr),right(nullptr){} 11 }; 12 vector<vector<int>> mirrorTree(Treenode* root) 13 { //返回值类型vector<vector<int>> 14 vector<vector<int>> result; 15 if(root==nullptr) return result; 16 queue<Treenode*> que; 17 que.push(root); 18 19 while(!que.empty()) 20 { 21 22 size_t q_size=que.size(); 23 vector<int> temp; 24 for(size_t i=0;i<q_size;++i) 25 { 26 Treenode* node=que.front(); 27 if(node->left) que.push(node->left); 28 if(node->right) que.push(node->right); 29 temp.push_back(node->val); 30 que.pop(); 31 } 32 reverse(temp.begin(),temp.end());//每一层反转 33 result.push_back(temp); 34 } 35 return result; 36 } 37 vector<vector<int>> mirrorTree_2(Treenode* root) 38 { 39 vector<vector<int>> result; 40 if(root==nullptr) return result; 41 queue<Treenode*> que; 42 que.push(root); 43 44 while(!que.empty()) 45 { 46 47 size_t q_size=que.size(); 48 vector<int> temp; 49 for(size_t i=0;i<q_size;++i) 50 { 51 Treenode* node=que.front(); 52 swap(node->left,node->right);//遍历之前交换左右节点 53 if(node->left) que.push(node->left); 54 if(node->right) que.push(node->right); 55 temp.push_back(node->val); 56 que.pop(); 57 } 58 59 result.push_back(temp); 60 } 61 return result; 62 } 63 int main() 64 { 65 66 Treenode* n1=new Treenode(1); 67 Treenode* n2=new Treenode(2); 68 Treenode* n3=new Treenode(3); 69 Treenode* n4=new Treenode(4); 70 Treenode* n6=new Treenode(6); 71 Treenode* n7=new Treenode(7); 72 Treenode* n9=new Treenode(9); 73 n4->left=n2; 74 n4->right=n7; 75 n2->left=n1; 76 n2->right=n3; 77 n7->left=n6; 78 n7->right=n9; 79 vector<vector<int>> re= mirrorTree_2(n4); 80 for(auto it:re) 81 { 82 for(auto it2:it) 83 { 84 cout<<it2<<" "; 85 } 86 } 87 return 0; 88 }
leetcode版:
class Solution { public://返回的值为TreeNode*类型 TreeNode* mirrorTree(TreeNode* root) {//也是层次遍历 queue<TreeNode*> que; if(root==nullptr) return root; que.push(root); while(!que.empty()) { TreeNode* node=que.front(); swap(node->left,node->right); if(node->left) que.push(node->left); if(node->right) que.push(node->right); que.pop(); } return root; } };
class Solution {//递归版,返回值TreeNode* public: void digui(TreeNode* root) { if(root==nullptr) return; swap(root->left,root->right); digui(root->left); digui(root->right); } TreeNode* mirrorTree(TreeNode* root) { digui(root); return root; } };