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);
        }
    }
    

      

  • 相关阅读:
    Game Engine Architecture 3
    Game Engine Architecture 2
    补码
    工厂模式
    Game Engine Architecture 1
    YDWE Keynote
    3D Math Keynote 4
    3D Math Keynote 3
    3D Math Keynote 2
    OGRE中Any 类型的实现
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11325609.html
Copyright © 2011-2022 走看看