一天一道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
    }
};

最新文章

  1. Vuforia结合Skyshop: Image-Based Lighting Tools &amp; Shaders插件实现真实的光照效果
  2. [转]JUnit-4.11使用报java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing错误
  3. javascript_core_04之数组API
  4. postgis数据库文件shapefile导入 dbf file (.dbf) can not be opened.shapefile import failed.
  5. 实现可以滑动的GrildView,类似美团网首页的GrildView功能菜单
  6. 【java】String类和StringBuffer类常用操作
  7. [MFC]MFC中OnDraw与OnPaint的区别
  8. opencv 图像仿射变换 计算仿射变换后对应特征点的新坐标 图像旋转、缩放、平移
  9. C# 编辑距离实现
  10. Gitlab使用Webhook实现Push代码自动部署
  11. ES6的开发环境搭建
  12. 前端技术之--HTML
  13. height属性
  14. CSS选择器操作大全
  15. repo回退当前分支下所有仓库到指定日期前的最新代码版本【转】
  16. 多线程(Java)
  17. jdk8-lambda表达式的使用
  18. 惠普(HP)战66 Pro G1 - 批量GHOST[Win10专业版 ] (UEFI)
  19. Python预编译语句防止SQL注入
  20. 教程:让你的表单升级到CSS3和HTML5客户端验证

热门文章

  1. linux上安装fastdfs+nginx+ngin-module实践并解决多个异常篇
  2. fastDFS 安装 配置 使用
  3. 一个蒟蒻对FFT的理解(蒟蒻也能看懂的FFT)
  4. linux系统下安装jdk,mysql,tomcat 和redis 和jedis入门案例
  5. ubuntu15.10 opencv3.1 安装配置codeblocks
  6. 服务器&amp;阵列卡&amp;组raid 5
  7. 关于spring的IOC和DI的xml以及注解的简单介绍
  8. Django Views(视图函数)
  9. django+uwsgi+nginx+postgresql备忘
  10. shiro salt