Same Tree 判断俩树是不是一样
来源:互联网 发布:电脑分区软件 编辑:程序博客网 时间:2024/06/09 13:57
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.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
下边的这个是递归
出处:http://www.bubuko.com/infodetail-954959.html
public class Solution {public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null&&q==null) return true;
if(p==null||q==null) return false;
if(p.val!=q.val) return false;
return isSameTree(p.left, q.left)&&isSameTree(p.right, q.right);
}
}
下边的这个是迭代
出处:http://blog.csdn.net/xudli/article/details/8557010
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
Queue<TreeNode> q1 = new LinkedList<TreeNode>();
Queue<TreeNode> q2 = new LinkedList<TreeNode>();
q1.offer(p);
q2.offer(q);
while( !q1.isEmpty() && !q2.isEmpty() ) {
TreeNode x = q1.poll();
TreeNode y = q2.poll();
if(x==null) {
if( y!=null) return false;
else continue;
}
if(y==null || x.val!=y.val) return false;
q1.offer( x.left);
q1.offer( x.right);
q2.offer(y.left);
q2.offer(y.right);
}
return true;
}
}
- Same Tree 判断俩树是不是一样
- 100. Same Tree和判断一个树是不是对称的思想一样
- Same Tree 判断两棵树是不是相同
- Same Tree判断二叉树相等
- 【leetcode 二叉树相等判断】Same Tree
- Same Tree 判断相同的树
- Same Tree (判断树是否相等)
- 100. Same Tree |判断二叉树相同
- 100. Same Tree判断二叉树相等
- Symmetric Tree 判断树是不是对称的
- LeetCode OJ 之 Same Tree (相同树的判断)
- Leetcode Same Tree 判断两棵二叉树是否相同
- 100. Same Tree (判断二叉树是否相等)
- [LeetCode]100. Same Tree--判断二叉树是否相同
- Leetcode#100. Same Tree(判断两个二叉树相同)
- LeetCode-100-Same Tree 水题 判断二叉树相等
- LeetCode--Same Tree(判断两个二叉树是否相同)Python
- 007-100-判断两个二叉树是否相等 Same Tree
- Android项目里,strings文件中字符串的格式化用法
- 微信支付、公众号支付、微信APP支付教程
- win7上python+theano+keras安装
- 使用hexo创建github博客
- Android设置监听回调的方式
- Same Tree 判断俩树是不是一样
- libusb 块传输 同步传输例程
- 如何分析Android的Log
- java-NoSuchMethodError问题解决——傻瓜式
- 蓝懿iOS 技术内容和心得 16.1.8
- JAVA中重写equals()方法的同时要重写hashcode()方法
- 【javaMail】【1.基础发邮件】java mail 发送plain text 邮件 helloworld
- IBatis配置一对一、一对多两种实现方式
- <LeetCode OJ> 326. Power of Three