题目如下:
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
解决办法如下:
package test;
public class LC100Try1
{
public boolean isSameTree(TreeNode p, TreeNode q)
{
boolean ret = false;
ret=getPass(p,q);
return ret;
}
public boolean getPass(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 getPass(p.left, q.left) && getPass(p.right, q.right);
}
}
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;
}
if(!isSameTree(p.left,q.left)){
return false;
}
if(!isSameTree(p.right,q.right)){
return false;
}
return true;
}
哈哈