请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

// test20.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<vector>
#include<string>
#include<queue>
#include<stack>

using namespace std;



struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
	val(x), left(NULL), right(NULL) {
	}
};
class Solution {
public:
	//层次遍历二叉树
	//都从上往下遍历;一个从左往右遍历,一个从右往左遍历;
	//如果得到的层次遍历结果一样,说明这棵树是对称二叉树
	//上面这种方法不可行,因为比如1 2 # # #和 1 # 2 # #就不是对称二叉树

	//方法2:构建镜像二叉树
	TreeNode *newTree=NULL;
	bool isSymmetrical(TreeNode* pRoot)
	{
		if (pRoot == NULL) return false;
		CreateImageTree(pRoot, newTree);
		bool result = judgeTwoTree(pRoot, newTree);
		return result;
	}
 void CreateImageTree(TreeNode* pRoot,TreeNode* &T)
	{
		if (pRoot == NULL) return;
		else
		{
			int num = pRoot->val;
			T = new TreeNode(num);
			CreateImageTree(pRoot->left,T->right);
			CreateImageTree(pRoot->right,T->left);
		}
	}
	 bool judgeTwoTree(TreeNode* T1,TreeNode* T2)
	 {
		 if (T1 == NULL && T2 == NULL) return true;
		 if (T1 != NULL && T2 == NULL) return false;
		 if (T1 == NULL && T2 != NULL) return false;
		 if (T1->val != T2->val) return false;
			 return judgeTwoTree(T1->right, T2->right) && judgeTwoTree(T1->left,T2->left);
	 }


	void preCreate(TreeNode* &T)
	{
		int num;
		cin >> num;
		if (num == 0) T = NULL;
		else
		{
			T = new TreeNode(num);
			preCreate(T->left);
			preCreate(T->right);
		}
	}

	void preOrder(TreeNode* T)
	{
		if (T == NULL) return; 
		else
		{
			cout << T->val << "  ";
			preOrder(T->left);
			preOrder(T->right);
		}
	}
};
int main()
{
	
	Solution so;
	TreeNode *T1;
	TreeNode *T2;
	vector<int> vec;

	cout << "创建T1:" << endl;
	so.preCreate(T1);
	cout << "创建T1成功!" << endl;



	cout << "T1的前序遍历:" << endl;
	so.preOrder(T1);
	cout << endl;

	//so.CreateImageTree(T1,T2);
	//cout << "T2的前序遍历是(T2是T1的镜像):"<<endl;
	//so.preOrder(T2);
	//cout << endl;

	cout << "T1是否是对称的:" ;
	bool re = so.isSymmetrical(T1);
	cout << re << endl;




	
	
	cout << endl;
	return 0;
}
posted @ 2016-10-24 20:33  wdan2016  阅读(565)  评论(0编辑  收藏  举报