树、递归————翻转二叉树
其实就是后序遍历
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode* invertTree(TreeNode* root) { 13 //相当于后序遍历 14 if(!root) return root; 15 swap(root->left,root->right); 16 invertTree(root->left); 17 invertTree(root->right); 18 return root; 19 } 20 };
c++
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) return; 14 swap(pRoot->left,pRoot->right); 15 Mirror(pRoot->left); 16 Mirror(pRoot->right); 17 } 18 };