100. Same Tree100. Same Tree
题目描述
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.
解题方法
比較架構
case 1: 當同為遇到null, 返true
case 2: 一則為空,返false
比較數值
確認data是否相同
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;
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}