【一天一道LeetCode】#100. Same Tree(100题大关)
2016-06-24 21:35
330 查看
一天一道LeetCode
本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处
(一)题目
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.
(二)解题
题目大意:比较两个二叉树是否相等解题思路:采用深度优先搜索,依次遍历两个树,判断每个节点是否相等。
博主利用栈实现非递归的二叉输深度优先搜索,并判断每个节点
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { stack<pair<TreeNode*,TreeNode*>> TwoTreeNode;//用栈实现非递归 TwoTreeNode.push(make_pair<TreeNode*,TreeNode*>((TreeNode*)p,(TreeNode*)q));//初始化 while(!TwoTreeNode.empty()) { auto temp = TwoTreeNode.top();//去除栈顶 TwoTreeNode.pop();//处理当前节点 TreeNode* ptemp = temp.first; TreeNode* qtemp = temp.second; if(ptemp==NULL&&qtemp==NULL) continue;//两个都为空 else if(ptemp!=NULL&&qtemp!=NULL){//两个都不为空 if(ptemp->val==qtemp->val)//判断值是否相等 { TwoTreeNode.push(make_pair(ptemp->left,qtemp->left));//相等则放入栈等待处理 TwoTreeNode.push(make_pair(ptemp->right,qtemp->right)); } else return false;//不相等返回false } else return false;//一个为空另一个不为空直接返回false } return true;//全部处理完都相等就返回true } };
相关文章推荐
- 刚看了一个学生用PY写的web聊天作业,写的不错,忍不住发一下。
- CSS权威指南-选择相邻兄弟元素
- 你真的了解OKR吗?
- AR模型(Autoregress)
- JAVA——对象的序列化Serializable
- JVM垃圾回收机制
- Learn Once ,Write Anywhere —— 从零开始学习React Native(一)搭建环境
- 专题四1002
- 前端团队技术分享(一)
- MySQL(一)
- 遮罩层——通过阴影弱化背景的四种方案
- 网络流刷题记录-最小割
- iOS 开发不可缺少的工具
- 提高项目9.1-歌手大奖赛计分系列2
- 解决httpclient上传文件的时候中文文件名乱码的问题
- 网易大厦和他的邻居们
- CSS中的几种选择器
- Linux C 库函数与系统调用的区别
- git之数据整理
- 舞蹈链(Dancing Links)算法