题目
给你一棵二叉树的根节点 root
,翻转这棵二叉树,并返回其根节点。
示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
示例 2:
给你一棵二叉树的根节点 root
,翻转这棵二叉树,并返回其根节点。
示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
示例 2:
输入:root = [2,1,3]
输出:[2,3,1]
示例 3:
输入:root = []
输出:[]
C++代码
cpp
#include <iostream>
using namespace std;
//定义二叉树结构体
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* left, TreeNode* right): val(x), left(left), right(right) {}
};
/*
* 翻转二叉树问题
* 保护左子树不变,迭代翻转左右子树
*/
TreeNode* invertTree(TreeNode* root) {
if (root == nullptr) {
return nullptr;
}
TreeNode* leftTree = root->left;
root->left = invertTree(root->right);
root->right = invertTree(root->left);
return root;
}
int main() {
TreeNode* r1 = new TreeNode(4);
TreeNode* r2 = new TreeNode(2);
TreeNode* r3 = new TreeNode(7);
TreeNode* r4 = new TreeNode(1);
TreeNode* r5 = new TreeNode(3);
TreeNode* r6 = new TreeNode(6);
TreeNode* r7 = new TreeNode(9);
r1->left = r2;
r1->right = r3;
r2->left = r4;
r2->right = r5;
r3->left = r6;
r3->right = r7;
r4->left = nullptr;
r4->right = nullptr;
r5->left = nullptr;
r5->right = nullptr;
r6->left = nullptr;
r6->right = nullptr;
r7->left = nullptr;
r7->right = nullptr;
TreeNode* root = r1;
TreeNode* ans = invertTree(root);
delete r1, r2, r3, r4, r5, r6, r7;
return 0;
}
分析
翻转二叉树问题,保护左子树不变,迭代翻转左右子树。但是没有输出二叉树。