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 }
  • 相关阅读:
    GitLab备份与恢复
    内网穿透frp
    Python Day21-22(Django进阶)
    Python Day19-20(Django基础)
    Python Day18(Django初识)
    Python Day17(jQuery)
    Python day16(JavaScript)
    Python Day15(CSS)
    Unity组件
    关于游戏
  • 原文地址:https://www.cnblogs.com/huntfor/p/3881581.html
Copyright © 2011-2022 走看看