# 相同二叉樹和鏡面二叉樹問題

CSDN：相同二叉樹和鏡面二叉樹問題

## 判斷兩棵樹是否是相同的樹

``````if (p == null || q == null) {
// 兩個同時爲空才表示 same tree
return q == null && p == null;
}
``````

``````p.val == q.val
``````

``````return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
``````

``````public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null || q == null) {
// 兩個樹同時爲空才表示 same tree
return q == null && p == null;
}
return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
``````

## 鏡面二叉樹問題

``````if (null == root) {
return true;
}
``````

``````if (root.left == null || root.right == null) {
return root.left == null && root.right == null;
}
``````

``````boolean isSymmetric(TreeNode left, TreeNode right)
``````

base case 是

``````if (left == null || right == null) {
// 兩棵樹同時爲空才鏡面對稱
return left == null && right == null;
}
``````

``````public boolean isSymmetric(TreeNode left, TreeNode right) {
if (left == null || right == null) {
return left == null && right == null;
}
// left.val == right.val
return left.val == right.val && isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
}
``````

``````public boolean isSymmetric(TreeNode root) {
if (null == root) {
return true;
}
if (root.left == null || root.right == null) {
return root.left == null && root.right == null;
}
return root.left.val == root.right.val && isSymmetric(root.left, root.right);
}
``````