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 1
/ \ / \
2 2 and 2 2
/ /
4 4
就是两棵等价的二叉树。
1 1
/ \ / \
2 3 and 2 3
/ \
4 4
就不是等价的。
这道题思路很简单,递归检查每个结点的左右子树是否相等即可。
代码如下:
/**
* 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;
}
if(p.val == q.val){
return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
}else{
return false;
}
}
}