翻转二叉树

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;




}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值