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.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public boolean isSameTree(TreeNode p, TreeNode q) {
/**
* 树的遍历采用递归算法
* isSameTree=isSameTree(left)+isSameTree(right)
*/
//当前子树相等
if (p == null && q == null) {
return true;
}
//不相等
if (p == null || q == null) {
return false;
}
if (p.val != q.val) {
//不相等
return false;
} else {
//无法判断,向下递归
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}