zoukankan      html  css  js  c++  java
  • symmetric-tree

    /**
    * Given a binary tree, check whether it is a mirror of itself
    * (ie, symmetric around its center).
    * 1
    * /
    * 2 2
    * / /
    * 3 4 4 3
    *
    * 对于二叉树,检查它是否是自身的镜像(即,围绕其中心对称)。
    * 例如,此二叉树是对称的:
    * 1
    * /
    * 2 2
    * / /
    * 3 4 4 3
    */

    /**
     * Given a binary tree, check whether it is a mirror of itself
     * (ie, symmetric around its center).
     *     1
     *    / 
     *   2   2
     *  /  / 
     * 3  4 4  3
     *
     * 对于二叉树,检查它是否是自身的镜像(即,围绕其中心对称)。
     * 例如,此二叉树是对称的:
     *     1
     *    / 
     *   2   2
     *  /  / 
     * 3  4 4  3
     */
    
    public class Main42 {
        public static void main(String[] args) {
            TreeNode root = new TreeNode(1);
            root.left = new TreeNode(2);
            root.right = new TreeNode(2);
            root.left.left = new TreeNode(3);
            root.right.right = new TreeNode(3);
            root.left.right = new TreeNode(5);
            root.right.left = new TreeNode(4);
            System.out.println(Main42.isSymmetric(root));
        }
    
        public static class TreeNode {
            int val;
            TreeNode left;
            TreeNode right;
            TreeNode(int x) { val = x; }
        }
    
        public static boolean isSymmetric(TreeNode root) {
            if (root == null) {
                return true;
            }
            return isEquals(root.left, root.right);
        }
    
        public static boolean isEquals(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 isEquals(root1.left, root2.right) && isEquals(root1.right, root2.left);
        }
    }
    

      

  • 相关阅读:
    TCP/IP笔记 一.综述
    Makefile的规则
    u盘安装ubuntu10.04 server.txt
    浅谈数据库技术,磁盘冗余阵列,IP分配,ECC内存,ADO,DAO,JDBC
    cocos2d-js 热更新具体解释(一)
    C#一个托付的样例
    JAVA学习之 异常处理机制
    阿里巴巴校招内推简历筛选方案
    《凑硬币》 动态规划算法入门
    android 读取xml
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11325609.html
Copyright © 2011-2022 走看看