5.1.9—二叉树的遍历—Symmetric Tree

本文介绍了一种用于检查二叉树是否对称的方法,包括递归和迭代两种实现方式,并提供了完整的C++代码示例及测试用例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same
value.

#include "BinaryTree.h"
#include <stack>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
//===判断一棵二叉树是否对称------递归版本
bool IsSymmetricTwoTree(BinaryTreeNode *proot1, BinaryTreeNode *proot2)
{
	if (!proot1&&!proot2) return true;
	else if (!proot1 || !proot2) return false;
	else
	{
		return (proot1->m_nValue == proot2->m_nValue)
			&& IsSymmetricTwoTree(proot1->m_pLeft, proot2->m_pRight)
			&& IsSymmetricTwoTree(proot1->m_pRight, proot2->m_pLeft);
	}
}
bool IsSymmetric1(BinaryTreeNode *proot)
{
	if (!proot) return true;
	else return IsSymmetricTwoTree(proot->m_pLeft, proot->m_pRight);
}
//===判断一棵二叉树是否对称------迭代版本
bool IsSymmetric2(BinaryTreeNode *proot)
{
	if (!proot) return true;

	stack<BinaryTreeNode*> temp;
	temp.push(proot->m_pLeft);
	temp.push(proot->m_pRight);
	while (!temp.empty())
	{
		auto p= temp.top();
		temp.pop();
		auto q = temp.top();
		temp.pop();
		if (!p&&!q) continue;
		if (!p || !q) return false;
		if (p->m_nValue != q->m_nValue) return false;

		temp.push(q->m_pLeft);
		temp.push(p->m_pRight);
		temp.push(q->m_pRight);
		temp.push(p->m_pLeft);
	}
	return true;
}

// ====================测试代码====================
//            8
//        6      6
//       9 9    9  9
int main()
{
	//===
	BinaryTreeNode* pNode8 = CreateBinaryTreeNode(8);
	BinaryTreeNode* pNode6 = CreateBinaryTreeNode(6);
	BinaryTreeNode* pNode10 = CreateBinaryTreeNode(6);
	BinaryTreeNode* pNode5 = CreateBinaryTreeNode(9);
	BinaryTreeNode* pNode7 = CreateBinaryTreeNode(9);
	BinaryTreeNode* pNode9 = CreateBinaryTreeNode(9);
	BinaryTreeNode* pNode11 = CreateBinaryTreeNode(5);

	ConnectTreeNodes(pNode8, pNode6, pNode10);
	ConnectTreeNodes(pNode6, pNode5, pNode7);
	ConnectTreeNodes(pNode10, pNode9, pNode11);
	
	//===
	//PrintTree(pNode8);
	//===
	bool flag1 = IsSymmetric1(pNode8);
	cout << flag1 << endl;
	//===
	bool flag2 = IsSymmetric2(pNode8);
	cout << flag2 << endl;

	DestroyTree(pNode8);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值