首页 > 代码库 > Same Tree leetcode java
Same Tree leetcode java
题目:
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.
题解:
递归判断左右是否相等。
代码如下:
1 public boolean isSameTree(TreeNode p, TreeNode q) {
2 if(p==null&&q==null)
3 return true;
4
5 if(p==null&&q!=null)
6 return false;
7
8 if(p!=null&&q==null)
9 return false;
10
11 if(p.val!=q.val)
12 return false;
13 boolean isleftsame = isSameTree(p.left,q.left);
14 if(!isleftsame)
15 return false;
16
17 boolean isrightsame = isSameTree(p.right,q.right);
18 if(!isrightsame)
19 return false;
20
21 return true;
22
23 }
2 if(p==null&&q==null)
3 return true;
4
5 if(p==null&&q!=null)
6 return false;
7
8 if(p!=null&&q==null)
9 return false;
10
11 if(p.val!=q.val)
12 return false;
13 boolean isleftsame = isSameTree(p.left,q.left);
14 if(!isleftsame)
15 return false;
16
17 boolean isrightsame = isSameTree(p.right,q.right);
18 if(!isrightsame)
19 return false;
20
21 return true;
22
23 }
对上述代码更简洁的写法是:
1 public boolean isSameTree(TreeNode p, TreeNode q) {
2 if(p == null&&q == null)
3 return true;
4 if(p == null||q == null)
5 return false;
6 return (p.val == q.val) && isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
7 }
2 if(p == null&&q == null)
3 return true;
4 if(p == null||q == null)
5 return false;
6 return (p.val == q.val) && isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
7 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。