代码实现:
方法1:先序遍历
/*** Definition for a binary tree node.* struct TreeNode {* int val;* struct TreeNode *left;* struct TreeNode *right;* };*/// 交换左右子树 void swap(struct TreeNode *root) {struct TreeNode *l = root->left;struct TreeNode *r = root->right;root->left = r;root->right = l; }// 递归:先序遍历 void pre_order(struct TreeNode *root) {if (root == NULL) {return ;}swap(root); // 交换pre_order(root->left);pre_order(root->right); }struct TreeNode* invertTree(struct TreeNode *root) {pre_order(root);return root; }
方法2:后序遍历
/*** Definition for a binary tree node.* struct TreeNode {* int val;* struct TreeNode *left;* struct TreeNode *right;* };*/// 交换左右子树 void swap(struct TreeNode *root) {struct TreeNode *l = root->left;struct TreeNode *r = root->right;root->left = r;root->right = l; }// 递归:后序遍历 void pre_order(struct TreeNode *root) {if (root == NULL) {return ;}pre_order(root->left);pre_order(root->right);swap(root); // 交换 }struct TreeNode* invertTree(struct TreeNode *root) {pre_order(root);return root; }