您的位置:首页 > 其它

翻转二叉树

2015-07-22 10:52 197 查看
1.二叉树初始化,插入数值,填满二叉树

2.按层打印原始二叉树

3.翻转二叉树

4.按层打印翻转后的二叉树

代码如下:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;

};

class Solution{
public:
TreeNode *invertTree(TreeNode *root)
{
if (root == NULL)
return NULL;
TreeNode *tmp;

tmp = root->left;
root->left = root->right;
root->right = tmp;

invertTree(root->left);
invertTree(root->right);

return root;
}
};

TreeNode *Insert(int x, TreeNode *root)
{
if (root == NULL)
{
root = (TreeNode *)malloc(sizeof(struct TreeNode));
if (root == NULL)
{
return NULL;
}
else
{
root->val = x;
root->left = NULL;
root->right = NULL;
}

}
else
{
if (x < root->val)
{
root->left=Insert(x,root->left);
}
else if (x > root->val)
{
root->right=Insert(x,root->right);
}
}
return root;
}

TreeNode *print(TreeNode *root)
{

if (root == NULL)
return NULL;

vector<TreeNode *> vec;
vec.push_back(root);
int cur = 0;
int last = 1;

while (cur < vec.size())
{
last = vec.size();
while (cur < last)
{

cout << vec[cur]->val << " ";
if (vec[cur]->left != NULL)
vec.push_back(vec[cur]->left);
if (vec[cur]->right != NULL)
vec.push_back(vec[cur]->right);

++cur;
}

}

}

int main(int argc, char *argv[])
{
vector<int> num = {4,2,7,1,3,6,9};
TreeNode* T = NULL;

for (auto s1 = num.begin(); s1 != num.end(); ++s1)
{
T=Insert(*s1,T);
}

print(T);
Solution Test;
Test.invertTree(T);
cout << endl;
print(T);

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: