28.对称的二叉树

对称的二叉树.png
  • 思路:
    (1)求出该二叉树的镜像二叉树的数组(注要包括子节点为null的值),比较二叉树的数组与镜像二叉树的数组是否完全相同,若完全能相同则为True,反之为False。
    (2) 观察可以发现,如果该二叉树的先序遍历与自定义的遍历方式(根->右->左)匹配的值完全相同则为对称而叉树---------推荐
  • 具体代码如下:
/**
 * @program: soft_test
 * @description: 对称二叉树
 * 请实现一个函数,用来判断一棵二叉树是不是对称的。
 * 如果一棵二叉树和它的镜像一样,那么它是对称的。
 *      1
 *    / \
 *   2   2
 *  / \ / \
 * 3  4 4  3
 * 对称
 *
 *      1
 *    / \
 *   2   2
 *    \   \
 *    3    3
 *  不对称
 * @author: Mr.zuo
 * @create: 2021-01-11 12:39
 **/

public class IsSymmetric {
    public static void main(String[] args) {

        // 初始化二叉树并赋值。
        TreeNode node = new TreeNode(1);
        node.left = new TreeNode(2);
        node.right = new TreeNode(2);
        node.left.left = new TreeNode(3);
        node.left.right = new TreeNode(4);
        node.right.left = new TreeNode(4);
        node.right.right = new TreeNode(0);;
        boolean symmetric = isSymmetric(node);
        System.out.println(symmetric);

    }

    /**
     * 自定义一个遍历算法与先序遍历类似:根->右->左
     * */
    public static boolean isSymmetric(TreeNode root) {
        return isSymmetric(root, root);
    }

    /**
     * 比较使用先序遍历算法遍历树1与使用自定义遍历算法遍历的树2是否完全相同
     * */
    public static boolean isSymmetric(TreeNode root1,TreeNode root2) {
       if (root1 == null && root2 == null){
           return true;
       }
       if (root1 == null || root2 == null){
           return false;
       }
       if (root1.val != root2.val){
           return false;
       }
       // 先序遍历根->左->右与自定义遍历方法:根->右->左所输出的值完全对应则为对称二叉树
       return isSymmetric(root1.left,root2.right) && isSymmetric(root1.right,root2.left);
    }

}

你可能感兴趣的:(28.对称的二叉树)