leetcode 101

对称二叉树

Posted by Static on May 31, 2020

题目链接:https://leetcode-cn.com/problems/symmetric-tree/

题目描述


分析

1. 递归

将头节点的左右子树拆分为两个数,同时先序遍历左子树和镜像先序遍历右子树,对比数值

2. 层级遍历

todo ,层级遍历每一层,记录到list中,空节点也要记录,最后对每一层的左右两侧节点数值对比


代码实现

public enum  Q101 {

    instance;

    // 递归
    public boolean isSymmetric(TreeNode root) {
        if(root==null) return true;
        return isSymmetric(root.left,root.right);
    }

    private boolean isSymmetric(TreeNode left, TreeNode right) {

        if(left!=null&&right!=null){
            if(left.val==right.val){
                return isSymmetric(left.left,right.right)&&isSymmetric(left.right,right.left);
            }else {
                return false;
            }
        }else if(left==null&&right==null){
            return true;
        }else {
            return false;
        }
    }

    public static void main(String[] args) {
        TreeNode root1=new TreeNode(1);
        root1.left=new TreeNode(2);
        root1.right=new TreeNode(2);
        root1.left.left=new TreeNode(3);
        root1.left.right=new TreeNode(4);
        root1.right.left=new TreeNode(4);
        root1.right.right=new TreeNode(3);
        // assert true
        System.out.println(Q101.instance.isSymmetric(root1));

        TreeNode root2=new TreeNode(3);
        root2.left=new TreeNode(4);
        root2.right=new TreeNode(4);
        root2.left.left=new TreeNode(5);
        root2.right.right=new TreeNode(5);
        root2.left.left.left=new TreeNode(6);
        root2.right.right.right=new TreeNode(6);
        // assert true
        System.out.println(Q101.instance.isSymmetric(root2));

    }
}