首页 > 代码库 > leetcode------Same Tree
leetcode------Same Tree
标题: | Same Tree |
通过率: | 42% |
难度 | 简单 |
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.
这道题是自己的失误造成了第一次提交的失败,原因是题目没有看清楚。然后是对于二叉树的相同没有弄明白,如果想用对比节点相同的话还是要重写equals方法,显然本题是不能用的,那么就是节点的值比较,左右子树递归,具体步骤如下:
1、p、q两树均为空则返回true
2、p、q两树有且仅有一个树为空则返回false
3、p、q两树的节点值相同,则继续进行递归。
4、其他情况全部返回false
对于继续递归,则要用 (p.right,q.right)&&(p.left,q.left)两树左右都相同才能是完全的相同。这个题目直接看代码则能看出算法的步骤
1 public class Solution { 2 public boolean isSameTree(TreeNode p, TreeNode q) { 3 return vistree(p,q); 4 } 5 public boolean vistree(TreeNode p,TreeNode q){ 6 if(p==null&&q==null) return true; 7 if(p==null&&q!=null) return false; 8 if(p!=null&&q==null) return false; 9 if(p.val==q.val){10 return vistree(p.right,q.right)&&vistree(p.left,q.left);11 }12 else return false;13 }14 }
leetcode------Same Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。