题目:
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; }
* }
*/
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null){
return true;
}else if(p != null && q == null){
return false;
}else if(p == null && q != null){
return false;
}else{
boolean value, left, right;
//判断值是否相同
if(p.val == q.val){
value = true;
}else{
value = false;
}
//判断左右子树是否分别相同
left = isSameTree(p.left, q.left);
right = isSameTree(p.right, q.right);
//只有值相同,左子树相同,右子树也相同,两棵树才相同
if(value && left && right){
return true;
}else{
return false;
}
}
}
}