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.

判断两个树是否相同,起是用递归很好解决,但是我一开始居然想使用前序加中序遍历来唯一确定一棵树:

 class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
vector<int>res1;
vector<int>res2;
if(p == NULL && q == NULL)
return true;
else if(p == NULL || q == NULL)
return false;
preorderTraversal(p, res1);
preorderTraversal(q, res2);
bool ans1 = res1 == res2;
res1.clear(), res2.clear();
infixTraversal(p, res1);
infixTraversal(q, res2);
bool ans2 = res1 == res2;
return res1 && res2; }
void preorderTraversal(TreeNode * p, vector<int> & res)
{
if(p == NULL) return;
res.push_back(p->val);
preorderTraversal(p->left, res);
preorderTraversal(p->right, res);
}
void infixTraversal(TreeNode * p, vector<int> & res)
{
if(p == NULL) return;
infixTraversal(p->left, res);
res.push_back(p->val);
infixTraversal(p->right, res);
}
};

然而并不可行,只能使用下面这一种方法:

 class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(!p && !q)
return true;
else if(!p && q)
return false;
else if(p && !q)
return false;
else{
if(p->val != q->val)
return false;
else
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
}
};

当然也可以采用迭代的方式来完成:

 /**
* 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) {
queue<TreeNode *> pQueue;
queue<TreeNode *> qQueue;
pQueue.push(p); //这里只能用队列而不能用栈,因为单向链表的性质决定
qQueue.push(q);
while(!pQueue.empty() && !qQueue.empty()){
TreeNode * pTmp = pQueue.front();
TreeNode * qTmp = qQueue.front();
pQueue.pop(), qQueue.pop();
if(!pTmp && !qTmp)
continue;
else if(pTmp && !qTmp || !pTmp && qTmp || pTmp->val != qTmp->val)
return false;
else{
pQueue.push(pTmp->left);
pQueue.push(pTmp->right);
qQueue.push(qTmp->left);
qQueue.push(qTmp->right);
}
}
return pQueue.empty() && qQueue.empty();
}
};

下面是java代码:

递归的:

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null)
return true;
else if(p == null)
return false;
else if(q == null)
return false;
else{
if(p.val == q.val){
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}else
return false;
}
}
}

迭代版:

 public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
Queue<TreeNode> queueP = new LinkedList<TreeNode>();
Queue<TreeNode> queueQ = new LinkedList<TreeNode>();
TreeNode p1, p2;
queueP.add(p);
queueQ.add(q);
while(!queueP.isEmpty() && !queueQ.isEmpty()){
p1 = queueP.poll();
p2 = queueQ.poll();
if(p1 == null && p2 != null ||
p1 != null && p2 == null)
return false;
if(p1 == null && p2 == null)
continue;
if(p1.val == p2.val){
queueP.add(p1.left);
queueP.add(p1.right);
queueQ.add(p2.left);
queueQ.add(p2.right);
}else return false;
}
if(queueP.isEmpty() && queueQ.isEmpty())
return true;
return false;
}
}

LeetCode OJ:Same Tree(相同的树)的更多相关文章

  1. LeetCode OJ Symmetric Tree 判断是否为对称树(AC代码)

      思路: 主要判断左子树与右子树. 在判断左时,循环下去肯定会到达叶子结点中最左边的结点与最右边的结点比较. 到了这一步因为他们都没有左(右)子树了,所以得开始判断这两个结点的右(左)子树了. 当某 ...

  2. LeetCode OJ——Binary Tree Inorder Traversal

    http://oj.leetcode.com/problems/binary-tree-inorder-traversal/ 树的中序遍历,递归方法,和非递归方法. /** * Definition ...

  3. [LeetCode] Graph Valid Tree 图验证树

    Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), ...

  4. LeetCode 101. Symmetric Tree (对称树)

    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For e ...

  5. 【LeetCode】Same Tree(相同的树)

    这道题是LeetCode里的第100道题. 这是题目: 给定两个二叉树,编写一个函数来检验它们是否相同. 如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的. 示例 1: 输入: 1 1 ...

  6. [LeetCode OJ] Symmetric Tree

    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For e ...

  7. LeetCode 101. Symmetric Tree 判断对称树 C++

    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For e ...

  8. [leetcode]100. Same Tree相同的树

    Given two binary trees, write a function to check if they are the same or not. Two binary trees are ...

  9. LeetCode 100. Same Tree相同的树 (C++)

    题目: Given two binary trees, write a function to check if they are the same or not. Two binary trees ...

  10. LeetCode 101. Symmetric Tree(镜像树)

    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For e ...

随机推荐

  1. 剑指offer 面试26题

    面试26题: 题目:树的子结构 题:输入两棵二叉树A和B,判断B是不是A的子结构. 解题思路:递归,注意空指针的情况. 解题代码: # -*- coding:utf-8 -*- # class Tre ...

  2. 系统性能模块psutil

    psutil是一个跨平台库,能够轻松实现获取系统运行的进程和系统利用率(包括cpu.内存.磁盘.网络等)信息.它主要用于系统监控,分析和限制系统资源及进程的管理.它实现了同等命令行工具提供的功能,如p ...

  3. [笔记] Access Control Lists (ACL) 学习笔记汇总

    一直不太明白Windows的ACL是怎么回事,还是静下心来看一手的MSDN吧. [翻译] Access Control Lists [翻译] How Access Check Works Modify ...

  4. iOS objc_setAssociatedObject 关联对象的学习

    今天看了FDTemplateLayoutCell的源码,类别里面相当频繁使用了关联对象,做笔记!!!学套路 主要函数: void objc_setAssociatedObject(id object, ...

  5. $Java-json系列(二):用JSONObject解析和处理json数据

    本文中主要介绍JSONObject处理json数据时候的一些常用场景和方法. (一)jar包下载 所需jar包打包下载百度网盘地址:https://pan.baidu.com/s/1c27Uyre ( ...

  6. FTP下载

    import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import ja ...

  7. 关于Class.getResourceAsStream

    Properties properties = new Properties();    properties.load(new  InputStreamReader(CharactorTest.cl ...

  8. 20145230《java程序设计》第三次试验报告

    20145208 实验三 Java面向对象程序设计 实验内容 实验内容 初步掌握单元测试和TDD 理解并掌握面向对象三要素:封装.继承.多态 初步掌握UML建模 熟悉S.O.L.I.D原则 了解设计模 ...

  9. iOS面试必备-iOS基础知识

    近期为准备找工作面试,在网络上搜集了这些题,以备面试之用. 插一条广告:本人求职,2016级应届毕业生,有开发经验.可独立开发,低薪求职.QQ:895193543 1.简述OC中内存管理机制. 答:内 ...

  10. 常用java开发工具快捷键

    在这里列举一些开发中常用的快捷键 常用的idea的快捷键: 1.删除当前行:Ctrl+X 2.格式化代码:Ctrl+Alt+L 3.查看本页里面的内容:Ctrl+F 4.查看类的继承方式:Ctrl+H ...