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

    题目:

    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

    题意及分析:判断一棵树是不是左右对称。直接使用递归的方式,对根节点的左右子树,对左子树进行中左右,对右子树进行中右左遍历,判断每个节点是否相同。

    代码:

    /**
     * Definition for a binary tree node.
     * 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 isSymmetricTwo(root.left,root.right);
        }
    
        public boolean isSymmetricTwo(TreeNode node1,TreeNode node2){
            if((node1!=null&&node2==null)||(node1==null&&node2!=null)) return false;        //一边有一遍没有那么直接返回false
            if(node1==null&&node2==null) return true;
            if(node1.val==node2.val)
                return isSymmetricTwo(node1.left,node2.right)&&isSymmetricTwo(node1.right,node2.left);
            return false;
        }
    }
    

      

  • 相关阅读:
    NOIP2018 模拟赛(二十二)雅礼NOI
    浅谈左偏树在OI中的应用
    HDU3062&&HDU1814
    2-SAT超入门讲解
    bitset常用用法&&简单题分析
    NOIp2014提高组初赛错题简析
    2018十月刷题列表
    BZOJ 4804: 欧拉心算
    Luogu P2568 GCD
    Luogu P4137 Rmq Problem / mex
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7192944.html
Copyright © 2011-2022 走看看