LeetCode-Easy刷题(20) Symmetric Tree

Posted 当以乐

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-Easy刷题(20) 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.


检查一个树是否是对称的,用递归或者迭代解决最好.
//树的遍历--->结束条件
    public boolean isSymmetric(TreeNode root) 

        if(root ==null)
            return true;
        
        return isSymmetricHelp(root.left, root.right);
    

    public boolean isSymmetricHelp(TreeNode left,TreeNode right)
        if(left ==null && right ==null)
            return true;
        
        if(left ==null ||right ==null)
            return false;
        
        if(left.val !=right.val)
            return false;
        
        //左右对称
        return isSymmetricHelp(left.left, right.right) && isSymmetricHelp(left.right, right.left);
    


以上是关于LeetCode-Easy刷题(20) Symmetric Tree的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-Easy刷题 Valid Parentheses

LeetCode-Easy刷题(31) Single Number

LeetCode-Easy刷题 Remove Element

LeetCode-Easy刷题(19) Same Tree

LeetCode-Easy刷题(33) Min Stack

LeetCode-Easy刷题(33) Min Stack