題目說明:給你兩棵樹,要你判斷兩棵樹是否對稱
Case 1
Input: root = [1,2,2,3,4,4,3]
Output: true
Case 2
Input: root = [1,2,2,null,3,null,3]
Output: false
解題思路:要判斷兩種情況
附上程式碼以及註解
Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return symmetric(root.left,root.right);
}
public boolean symmetric(TreeNode n1,TreeNode n2){
if(n1==null&&n2==null)return true;
if(n1==null||n2==null)return false;
if(n1.val==n2.val){
return symmetric(n1.left,n2.right)&&symmetric(n1.right,n2.left);
}
return false;
}
}