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

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:

Input:     1         1
/ \ / \
2 3 2 3 [1,2,3], [1,2,3] Output: true

Example 2:

Input:     1         1
/ \
2 2 [1,2], [1,null,2] Output: false

Example 3:

Input:     1         1
/ \ / \
2 1 1 2 [1,2,1], [1,1,2] Output: false

判断两棵树是否相同和之前的判断两棵树是否对称都是一样的原理,利用深度优先搜索 DFS 来递归。代码如下:

解法一:

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

这道题还有非递归的解法,因为二叉树的四种遍历(层序,先序,中序,后序)均有各自的迭代和递归的写法,这里我们先来看先序的迭代写法,相当于同时遍历两个数,然后每个节点都进行比较,可参见之间那道 Binary Tree Preorder Traversal,参见代码如下:

解法二:

class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
stack<TreeNode*> st;
st.push(p); st.push(q);
while (!st.empty()) {
p = st.top(); st.pop();
q = st.top(); st.pop();
if (!p && !q) continue;
if ((p && !q) || (!p && q) || (p->val != q->val)) return false;
st.push(p->right); st.push(q->right);
st.push(p->left); st.push(q->left);
}
return true;
}
};

也可以使用中序遍历的迭代写法,对应之前那道 Binary Tree Inorder Traversal,参见代码如下:

解法三:

class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
stack<TreeNode*> st;
while (p || q || !st.empty()) {
while (p || q) {
if ((p && !q) || (!p && q) || (p->val != q->val)) return false;
st.push(p); st.push(q);
p = p->left; q = q->left;
}
p = st.top(); st.pop();
q = st.top(); st.pop();
p = p->right; q = q->right;
}
return true;
}
};

对于后序遍历的迭代写法,貌似无法只是用一个栈来做,因为每次取出栈顶元素后不立马移除,这样使用一个栈的话两棵树结点的位置关系就会错乱,分别使用各自的栈就好了,对应之前那道 Binary Tree Postorder Traversal,参见代码如下:

解法四:

class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
stack<TreeNode*> st1, st2;
TreeNode *head1, *head2;
while (p || q || !st1.empty() || !st2.empty()) {
while (p || q) {
if ((p && !q) || (!p && q) || (p->val != q->val)) return false;
st1.push(p); st2.push(q);
p = p->left; q = q->left;
}
p = st1.top();
q = st2.top();
if ((!p->right || p->right == head1) && (!q->right || q->right == head2)) {
st1.pop(); st2.pop();
head1 = p; head2 = q;
p = nullptr; q = nullptr;
} else {
p = p->right;
q = q->right;
}
}
return true;
}
};

对于层序遍历的迭代写法,其实跟先序遍历的迭代写法非常的类似,只不过把栈换成了队列,对应之前那道 Binary Tree Level Order Traversal,参见代码如下:

解法五:

class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
queue<TreeNode*> que;
que.push(p); que.push(q);
while (!que.empty()) {
p = que.front(); que.pop();
q = que.front(); que.pop();
if (!p && !q) continue;
if ((p && !q) || (!p && q) || (p->val != q->val)) return false;
que.push(p->right); que.push(q->right);
que.push(p->left); que.push(q->left);
}
return true;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/100

类似题目:

Binary Tree Preorder Traversal

Binary Tree Inorder Traversal

Binary Tree Postorder Traversal

Binary Tree Level Order Traversal

参考资料:

https://leetcode.com/problems/same-tree/

https://leetcode.com/problems/same-tree/discuss/32684/My-non-recursive-method

https://leetcode.com/problems/same-tree/discuss/32687/Five-line-Java-solution-with-recursion

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Same Tree 判断相同树的更多相关文章

  1. [LeetCode] Symmetric Tree 判断对称树

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

  2. [Leetcode] Same tree判断是否为相同树

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

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

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

  4. 二叉树系列 - [LeetCode] 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 (判断相同树)

    题意:如题 思路:递归解决,同判断对称树的原理差不多.先保证当前两个结点是相等的,再递归保证两左结点是相等的,再递归保证右结点是相等的. /** * Definition for a binary t ...

  6. 【LeetCode】572. 另一个树的子树 Subtree of Another Tree(Python & Java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:先序遍历 方法二:DFS + DFS 方法三 ...

  7. EasyUI Tree判断节点是否是叶

    方法1:  $('#domaincatalog').tree('isLeaf', node.target); 返回true或false ,true表示是叶节点, false即不是 方法2:官方文档中: ...

  8. LeetCode: Binary Tree Traversal

    LeetCode: Binary Tree Traversal 题目:树的先序和后序. 后序地址:https://oj.leetcode.com/problems/binary-tree-postor ...

  9. 【IT笔试面试题整理】判断一个树是否是另一个的子树

    [试题描述]定义一个函数,输入判断一个树是否是另一个对的子树 You have two very large binary trees: T1, with millions of nodes, and ...

随机推荐

  1. 认识W3C标准盒子模型,理解外边距叠加

    概述: 注:加粗斜体字是非常重要的概念,决定着你是不是能看懂那句话,所以不懂的请一定要搜索一下. 页面上的每个元素,都在一个矩形框里.   每个矩形框都是一个盒模型.   每个盒模型都由内容区域(co ...

  2. MySQL设置服务器方法

    grant select,insert,update,delete on *.* to root@"%" Identified by "root";

  3. 【Java每日一题】20161223

    package Dec2016; public class Ques1223 { public static void main(String[] args){ Integer obj = Integ ...

  4. 记录一次bug解决过程:git深入学习和JDK8新特性

    一 总结 熟悉廖雪峰git基础; 由于git跟踪的是修改,而不是版本号:因此对于修改撤销的操作,文件在eclipse中依旧有>修改标记,这点不同于svn. 二 BUG描述:熟悉Git基础 在Gi ...

  5. 《连载 | 物联网框架ServerSuperIO教程》- 5.轮询通讯模式开发及注意事项。附:网友制作的类库说明(CHM)

    1.C#跨平台物联网通讯框架ServerSuperIO(SSIO)介绍 <连载 | 物联网框架ServerSuperIO教程>1.4种通讯模式机制. <连载 | 物联网框架Serve ...

  6. poi读取excel模板,填充内容并导出,支持导出2007支持公式自动计算

    /** * 版权所有(C) 2016 * @author www.xiongge.club * @date 2016-12-7 上午10:03:29 */ package xlsx; /** * @C ...

  7. javascript实现键盘自动打字效果

    最近在网上看到一个字符逐个出现的打字效果,觉得挺有趣的,想一想基本实现思路就是设置一个定时器逐然后逐个向容器中添加字符,于是就基于jQuery写了一个简单版的. <!DOCTYPE html&g ...

  8. HTTP、HTTP2

      HTTP.HTTP2.0.SPDY.HTTPS 你应该知道的一些事 原文链接:http://www.alloyteam.com/2016/07/httphttp2-0spdyhttps-readi ...

  9. Atitit 《控制论原理与概论attilax总结

    Atitit <控制论原理与概论attilax总结 <控制论> 奠基之作,出自创始人维纳.虽然内容权威,但我认为带有相当强烈的个人色彩,且门槛较高,不适合入门.深入研究控制论必看书籍 ...

  10. [Android]使用自定义JUnit Rules、annotations和Resources进行单元测试(翻译)

    以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/5795091.html 使用自定义JUnit Rules.ann ...