5.1.9—二叉树的遍历—Symmetric Tree

来源:互联网 发布:浪潮软件重大新闻 编辑:程序博客网 时间:2024/05/22 10:40
描述
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  9int 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);}

原创粉丝点击