博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

程序员面试100题之十一,求二元查找树的镜像

Posted on 2010-09-24 14:41  KurtWang  阅读(154)  评论(0)    收藏  举报
// 100_11.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stack>

struct Node
{
	Node * left;
	Node * right;
	int value;
};

void mirror(Node * root)
{
	if(root==NULL)
		return;

	std::stack<Node*> s;
	s.push(root);

	while(!s.empty())
	{
		Node * cur = s.top();
		s.pop();

		Node * temp = cur->left;
		cur->left = cur->right;
		cur->right = temp;

		if(cur->left)
			s.push(cur->left);

		if(cur->right)
			s.push(cur->right);

		
	}
}


int _tmain(int argc, _TCHAR* argv[])
{
	Node * n1 = new Node();
	Node * n2 = new Node();
	Node * n3 = new Node();
	
	n1->left = n2;
	n1->right = n3;
	n1->value = 1;

	n2->left = NULL;
	n2->right = NULL;
	n2->value = 2;

	n3->left = NULL;
	n3->right = NULL;
	n3->value = 3;
	
	mirror(n1);

	return 0;
}