生成镜像树

递归生成镜像树

#include<iostream>
#include<stack>
#include<queue>
using namespace std;

class TreeNode {
public:
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int value):val(value),left(nullptr),right(nullptr){}
};

TreeNode *mirror(TreeNode *root) {
	if (!root) {
		return nullptr;
	}
	TreeNode *node = root->right;
	root->right = mirror(root->left);
	root->left = mirror(node);

	return root;
}

int main() {
	TreeNode *root = new TreeNode(4);
	TreeNode *a = new TreeNode(2);
	TreeNode *b = new TreeNode(7);
	TreeNode *c = new TreeNode(1);
	TreeNode *d = new TreeNode(3);
	TreeNode *e = new TreeNode(6);
	TreeNode *f = new TreeNode(9);
	root->left = a;
	root->right = b;
	a->left = c;
	a->right = d;
	b->left = e;
	b->right = f;

	TreeNode *res = mirror(root);

	queue<TreeNode*> s;
	s.push(res);
	while (!s.empty()) {
		int len = s.size();
		
		for (int i = 0; i < len; ++i) {
			TreeNode *cur = s.front();
			cout << cur->val << " ";
			if (cur->left) {
				s.push(cur->left);
			}
			if (cur->right) {
				s.push(cur->right);
			}
			s.pop();
		}
		
	}
	cout << endl;
	system("pause");
}

辅助栈实现

#include<iostream>
#include<stack>
#include<queue>
using namespace std;

class TreeNode {
public:
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int value):val(value),left(nullptr),right(nullptr){}
};

TreeNode *mirror(TreeNode *root) {
	if (root == nullptr) return nullptr;
	stack<TreeNode*> stack;
	stack.push(root);
	while (!stack.empty())
	{
		TreeNode* node = stack.top();
		stack.pop();
		if (node->left != nullptr) stack.push(node->left);
		if (node->right != nullptr) stack.push(node->right);
		TreeNode* tmp = node->left;
		node->left = node->right;
		node->right = tmp;
	}
	return root;
}

int main() {
	TreeNode *root = new TreeNode(4);
	TreeNode *a = new TreeNode(2);
	TreeNode *b = new TreeNode(7);
	TreeNode *c = new TreeNode(1);
	TreeNode *d = new TreeNode(3);
	TreeNode *e = new TreeNode(6);
	TreeNode *f = new TreeNode(9);
	root->left = a;
	root->right = b;
	a->left = c;
	a->right = d;
	b->left = e;
	b->right = f;

	TreeNode *res = mirror(root);

	queue<TreeNode*> s;
	s.push(res);
	while (!s.empty()) {
		int len = s.size();
		
		for (int i = 0; i < len; ++i) {
			TreeNode *cur = s.front();
			cout << cur->val << " ";
			if (cur->left) {
				s.push(cur->left);
			}
			if (cur->right) {
				s.push(cur->right);
			}
			s.pop();
		}
		
	}
	cout << endl;
	system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值