isSameTree1

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.

SOLUTION 1 & SOLUTION 2:

以下是递归及非递归解法:

1. 递归解法就是判断当前节点是不是相同,及左右子树是不是相同树

2. 非递归解法使用了先根遍历。这个算法比较简单一点

 /**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
// solution 1:
public boolean isSameTree1(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
} if (p == null || q == null) {
return false;
} return p.val == q.val &&
isSameTree(p.left, q.left) &&
isSameTree(p.right, q.right);
} // Solution 2:
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
} if (p == null || q == null) {
return false;
} Stack<TreeNode> s1 = new Stack<TreeNode>();
Stack<TreeNode> s2 = new Stack<TreeNode>(); s1.push(p);
s2.push(q); while (!s1.isEmpty() && !s2.isEmpty()) {
TreeNode cur1 = s1.pop();
TreeNode cur2 = s2.pop(); // 弹出的节点的值必须相等
if (cur1.val != cur2.val) {
return false;
} // tree1的right节点,tree2的right节点,可以同时不为空,也可以同时为空,否则返回false.
if (cur1.left != null && cur2.left != null) {
s1.push(cur1.left);
s2.push(cur2.left);
} else if (!(cur1.left == null && cur2.left == null)) {
return false;
} // tree1的左节点,tree2的left节点,可以同时不为空,也可以同时为空,否则返回false.
if (cur1.right != null && cur2.right != null) {
s1.push(cur1.right);
s2.push(cur2.right);
} else if (!(cur1.right == null && cur2.right == null)) {
return false;
}
} return true;
}
}

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/IsSameTree1.java

最新文章

  1. 虚拟机安装CentOS6.4
  2. 基于springMVC+angular+bootstrap+mysql的简易购物网站搭建
  3. objective-c(代码块)
  4. php验证是否是中文
  5. 固定虚拟机的IP
  6. PDF.NET框架操作——工具应用(一)
  7. Define custom @Required-style annotation in Spring
  8. NOIP2000 乘积最大
  9. PHP - Cookie 应用
  10. php等号(==)与全等(===)
  11. ios save image to album
  12. Object-C 基础学习笔记(for,foreach,while,switch)
  13. Chapter 2 Open Book——37
  14. 巧妙使用Contains()方法查找一个数是否在某堆数中
  15. CSDN发表文章后老是待审核的原因
  16. 工控随笔_08_西门子_Win10安装Step7.V5.6中文版授权管理器不能正常启动
  17. Vue 加载第三方插件
  18. 【51Nod1405】树上距离和 二次扫描与换根法
  19. React文档(三)介绍JSX
  20. GUI相关学习资料

热门文章

  1. redis_session_store.py
  2. js setInterval() 用法示例
  3. exeption ORA-00907: missing right parenthesis
  4. ASP.NET 性能监控和优化入门
  5. python 2.7疑难问题之 编码
  6. 创建简单的Telnet实例
  7. tomcat占用cpu过高解决办法
  8. ios block常见的错误(三)——并发编程的block引用
  9. SQLAlchemy基本使用(Flask中)
  10. nyoj-----D的小L