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).

    For example, this binary tree is symmetric:

        1
       / 
      2   2
     /  / 
    3  4 4  3
    

    But the following is not:

        1
       / 
      2   2
          
       3    3
    

    Note:
    Bonus points if you could solve it both recursively and iteratively.

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public class Node{
            public int val;
            public int pos;
            public Node(int val,int pos){
                this.val=val;
                this.pos=pos;
            }
        }
       public boolean isSymmetric(TreeNode root) {
            if(root==null) return true;
            else{
                ArrayList<Node> list=new ArrayList<Node>();
                copyBST(root,list,0);
                if(isSym(list)) return true;
                else return false;
            }
        }
        public boolean isSym(List<Node> list){
        	int n=list.size();
            for(int i=0;i<n/2;i++){
            	if(list.get(i).val!=list.get(n-i-1).val || (list.get(i).val==list.get(n-i-1).val && list.get(i).pos==list.get(n-i-1).pos )) return false;
            }
            return true;
        }
        public void copyBST(TreeNode root,List<Node> list,int pos){
            if(root==null) return;
            copyBST(root.left,list,1);
            Node node=new Node(root.val,pos);
            list.add(node);
            copyBST(root.right,list,2);
        }
    }

    这个解法感觉有问题的,但竟然ac了,留作记录,以下是正确的递归解法。

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        
       public boolean isSymmetric(TreeNode root) {
            if(root==null) return true;
            return isSym(root.left,root.right);
        }
        public boolean isSym(TreeNode left,TreeNode right){
        	if(left==null && right==null) return true;
        	if(left!=null && right==null) return false;
        	if(left==null && right!=null) return false;
        	if(left.val!=right.val) return false;
        	else return isSym(left.right,right.left)&&isSym(left.left,right.right);
        }
        
    }


  • 相关阅读:
    git线上操作
    IDEA快捷方式
    Java 四种线程池
    java 获取当前天之后或之前7天日期
    如何理解AWS 网络,如何创建一个多层安全网络架构
    申请 Let's Encrypt 通配符 HTTPS 证书
    GCE 部署 ELK 7.1可视化分析 nginx
    使用 bash 脚本把 AWS EC2 数据备份到 S3
    使用 bash 脚本把 GCE 的数据备份到 GCS
    nginx 配置 https 并强制跳转(lnmp一键安装包)
  • 原文地址:https://www.cnblogs.com/zhchoutai/p/6725122.html
Copyright © 2011-2022 走看看