Java算法_ 检查对称树(LeetCode_Hot100)

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

获得更多?算法思路:代码文档,算法解析的私得。

运行效果
Java算法_ 检查对称树(LeetCode_Hot100)_第1张图片

完整代码

/**
 * 2 * @Author: LJJ
 * 3 * @Date: 2023/8/17 8:47
 * 4
 */
public class SymmetricTree {

    static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int val){
            this.val = val;
        }
    }

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

    public static void main(String[] args) {
        SymmetricTree symmetricTree = new SymmetricTree();

        // 构建一个对称的二叉树
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(2);
        root.left.left = new TreeNode(3);
        root.left.right = new TreeNode(4);
        root.right.left = new TreeNode(4);
        root.right.right = new TreeNode(3);

        boolean isSymmetric = symmetricTree.isSymmetric(root);
        System.out.println("是否是轴对称的: " + isSymmetric); // 输出 true
    }
}

你可能感兴趣的:(java算法,算法,java,leetcode)