zoukankan      html  css  js  c++  java
  • 101. Symmetric Tree(树的对称)

    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

    For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

        1
       / 
      2   2
     /  / 
    3  4 4  3
    

    But the following [1,2,2,null,3,null,3] is not:

        1
       / 
      2   2
          
       3    3
    

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

    方法一:递归
    时间复杂度:o(n) 空间复杂度:o(1)
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        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) return true;
            if(left==null || right==null) return false;
            if(right.val != left.val) return false;
            return isSymmetric(left.left,right.right)&&isSymmetric(left.right,right.left); 
        }
    }
    方法二:迭代
    时间复杂度:o(n) 空间复杂度:o(1)
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean isSymmetric(TreeNode root) {
            Queue<TreeNode> q1=new LinkedList<TreeNode>();
            Queue<TreeNode> q2=new LinkedList<TreeNode>();
            q1.add(root);
            q2.add(root);
            while (!q1.isEmpty()&&!q2.isEmpty()){
                TreeNode t1=q1.poll();
                TreeNode t2=q2.poll();
                if(t1==null&&t2==null) continue;
                if(t1==null||t2==null) return false;
                if(t1.val!=t2.val) return false;
                q1.add(t1.left);
                q1.add(t1.right);
                q2.add(t2.right);
                q2.add(t2.left);
            }
            return true;
        }
    }
     
    苟有恒,何必三更眠五更起;最无益,莫过一日暴十日寒。
  • 相关阅读:
    SQL server 统计数据库表数量和列出所有表名称
    mybatis 模糊查询 like的三种方式
    jquery 实现按回车键登录功能的写法
    js 各种事件 如:点击事件、失去焦点、键盘事件等
    ssm框架中从controller传值给jsp的方式
    [GDOI2019]小说
    洛谷5113
    2020.9.26模拟总结
    [IOI2015]分组
    9.19 总结
  • 原文地址:https://www.cnblogs.com/shaer/p/10574331.html
Copyright © 2011-2022 走看看