zoukankan      html  css  js  c++  java
  • [leetcode]Symmetric Tree

    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.

    算法思路:

    思路:递归。镜像判断。

    代码如下:

     1 public class Solution {
     2     public boolean isSymmetric(TreeNode root) {
     3         if(root == null || (root.left == null && root.right == null)) return true;
     4         return isSym(root.left, root.right);
     5             
     6         
     7     }
     8     public boolean isSym(TreeNode left,TreeNode right){
     9         if(left == null && right == null) return true;
    10         if((left == null && right != null) || (left != null && right == null) || right.val != left.val) 
             return false; 11 return isSym(left.left, right.right) && isSym(left.right, right.left); 12 } 13 }
  • 相关阅读:
    bzoj 4260REBXOR
    bzoj 1009GT考试
    cf 621E. Wet Shark and Blocks
    cf 507E. Breaking Good
    cf 766#
    bzoj 3732Network
    bzoj 4300绝世好题
    bzoj 4345[POI2016]Korale
    bzoj 4236JOIOJI
    bzoj 4237稻草人
  • 原文地址:https://www.cnblogs.com/huntfor/p/3881581.html
Copyright © 2011-2022 走看看