101. 对称二叉树

发布于 2022-09-19  235 次阅读


给你一个二叉树的根节点 root , 检查它是否轴对称。

输入:root = [1,2,2,3,4,4,3]
输出:true
输入:root = [1,2,2,null,3,null,3]
输出:false
/**
 * 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 isOrder(root.left, root.right);
    }

    public static boolean isOrder(TreeNode root1, TreeNode root2) {
         
        if (root1==null&&root2==null){
            return true;
        }
        if (root1==null || root2==null){
            return false;
        }
        return root1.val==root2.val && isOrder(root1.left, root2.right) && isOrder(root1.right, root2.left);
    }
}

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户

内存消耗:39.4 MB, 在所有 Java 提交中击败了91.89%的用户