1.和leetcode中的Invert Binary Tree(easy)题目差不多
2.利用递归函数,每次都把左右子树翻转即可
函数如下:
void invertTree(TreeNode* root)
{
if (root != NULL)
{
swap(root->l, root->r);
invertTree(root->l);
invertTree(root->r);
}
}AC代码如下:
//#include<string>
//#include <iomanip>
#include<vector>
#include <algorithm>
//#include<stack>
#include<set>
#include<queue>
#include<map>
//#include<unordered_set>
#include<unordered_map>
//#include <sstream>
//#include "func.h"
//#include <list>
#include<stdio.h>
#include<iostream>
#include<string>
#include<memory.h>
#include<limits.h>
using namespace std;
struct TreeNode{
int val;
TreeNode*l, *r;
TreeNode() :val(-1),l(NULL), r(NULL){};
};
void invertTree(TreeNode* root)
{
if (root != NULL)
{
swap(root->l, root->r);
invertTree(root->l);
invertTree(root->r);
}
}
void levelOrder(TreeNode*root,vector<int>&ans)
{
queue<TreeNode*> q;
if (root != NULL)
{
q.push(root);
int count1 = 1;
int count2 = 0;
while (!q.empty())
{
for (int i = 0; i < count1; i++)
{
TreeNode* head = q.front(); q.pop();
ans.push_back(head->val);
if (head->l != NULL)
{
q.push(head->l);
count2++;
}
if (head->r != NULL)
{
q.push(head->r);
count2++;
}
}
count1 = count2;
count2 = 0;
}
}
}
void inOrder(TreeNode*root, vector<int>&ans)
{
if (root != NULL)
{
inOrder(root->l, ans);
ans.push_back(root->val);
inOrder(root->r, ans);
}
}
int main(void)
{
int sum;
cin >> sum;
vector<TreeNode> tree(sum);
vector<int> degree(sum,0);
for (int i = 0; i < sum; i++)
{
tree[i].val = i;
char a, b;
cin >> a >> b;
if (a!='-')
{
tree[i].l = &tree[a - '0'];
degree[a - '0']++;
}
if (b != '-')
{
tree[i].r = &tree[b - '0'];
degree[b - '0']++;
}
}
TreeNode* root=NULL;
for (int i = 0; i < sum; i++)
{
if (degree[i] == 0)
{
root = &tree[i];
break;
}
}
invertTree(root);
vector<int> ans1(0);
vector<int> ans2(0);
levelOrder(root, ans1);
inOrder(root, ans2);
for (int i = 0; i < ans1.size(); i++)
{
cout << ans1[i];
if (i != ans1.size() - 1)
cout << " ";
}
cout << endl;
for (int i = 0; i < ans2.size(); i++)
{
cout << ans2[i];
if (i != ans2.size() - 1)
cout << " ";
}
cout << endl;
return 0;
}
本文详细介绍了如何使用递归函数实现二叉树的翻转,并通过层次遍历和中序遍历展示了翻转后的二叉树结构。同时,提供了AC代码实现,包括翻转函数、层次遍历函数和中序遍历函数,帮助读者理解算法的实现细节。
303

被折叠的 条评论
为什么被折叠?



