zoukankan      html  css  js  c++  java
  • LeetCode 101. Symmetric Tree

    分析

    难度 易

    来源

    https://leetcode.com/problems/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.

    解答

    Runtime: 8 ms, faster than 98.44% of Java online submissions for Symmetric Tree.

     1 package LeetCode;
     2 
     3 public class L101_SymmetricTree {
     4     public boolean isAlike(TreeNode p, TreeNode q) {//把一棵树的对称转化为两棵树的相似
     5         if(p==null&&q==null)
     6             return true;
     7         if((p==null&&q!=null)||(p!=null&&q==null)||(p.val!=q.val))
     8             return false;
     9         return isAlike(p.left,q.right)&&isAlike(p.right,q.left);
    10     }
    11     public boolean isSymmetric(TreeNode root) {
    12         if(root==null)
    13             return true;
    14         return isAlike(root.left,root.right);
    15     }
    16 }

     

    博客园的编辑器没有CSDN的编辑器高大上啊
  • 相关阅读:
    320 Generalized Abbreviation
    319. Bulb Switcher
    三条用人原则
    Go 编码问题的解决方案
    C# MVC js 跨域
    apidoc接口文档的快速生成
    go语言学习
    C#系统之垃圾回收
    WCF项目启动时错误处理
    XML之XPath
  • 原文地址:https://www.cnblogs.com/flowingfog/p/9878993.html
Copyright © 2011-2022 走看看