LeetCode101 SynmetricTree Java question

Source: Internet
Author: User

LeetCode101 SynmetricTree Java question

Question:

 

Given a binary tree, check whether it is a mirror of itself (ie, shortric around its center ).

For example, this binary tree is unsupported Ric:

    1   / \  2   2 / \ / \3  4 4  3

 

But the following is not:

    1   / \  2   2   \   \   3    3

Solution:

Symmetry means that each layer is equal to right-to-left from left to right. There are two solutions: Non-recursion and recursion.

Non-recursion:

 

Public static boolean isSymmetric (TreeNode root) {if (root = null) return true; Queue
 
  
Left = new Queue list <> (); Queue
  
   
Right = new rule list <> (); if (root. left = null) left. offer (root. left); if (root. right = null) right. offer (root. right); while (! Left. isEmpty ()&&! Right. isEmpty () {TreeNode l = left. poll (); TreeNode r = right. poll (); if (l = null & r = null) continue; if (l = null | r = null) return false; if (l. val! = R. val) return false; left. offer (l. left); left. offer (l. right); right. offer (r. right); right. offer (r. left); // insert in reverse order to form an image} if (left. isEmpty () & right. isEmpty () return true; else {return false ;}}
  
 
Recursion:

 

 

 public boolean isSymmetric2(TreeNode root) { if(root==null) return true; else {return  isSame(root.left, root.right);}   }  public boolean isSame(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; else {return isSame(left.left, right.right)&&isSame(left.right, right.left);}  }



 

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.