# 1102. Invert a Binary Tree (25)

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++)
{
{
count2++;
}
{
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;
}


• 本文已收录于以下专栏：

举报原因： 您举报文章：1102. Invert a Binary Tree (25) 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)