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.