Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.1 kB
5
Indexable
Never
import java.util.*;
class Solution {
    public boolean isSymmetric(TreeNode root) {
        Queue<Pair<Integer,TreeNode>> queue = new LinkedList<>();
        List<Integer> list = new ArrayList<>();
        List<List<Integer>> listoflist = new ArrayList<>();
        Pair<Integer,TreeNode> p = new Pair(1,root);
        queue.add(p);
        while(!queue.isEmpty()){
            Pair<Integer,TreeNode> pair = queue.remove();
            TreeNode b = null;
            int temp = 0;
            if(pair!=null){
             b= pair.getValue();
             temp = pair.getKey(); 
            }
            
            if(b!=null){
                list.add(b.val);
            }
            
            
            if(b!=null && b.left !=null){
                Pair<Integer,TreeNode> p1 = new Pair(temp+1,b.left);
                queue.add(p1);
                
            }
            else if (b!=null){
                queue.add(null);
            }
            
            if(b!=null && b.right !=null){
                Pair<Integer,TreeNode> p1 = new Pair(temp+1,b.right);
                queue.add(p1);
                
            }
            else if (b!=null){
                queue.add(null);
            }
            
            if(listoflist.size()<temp){
                listoflist.add(new ArrayList<>());
            }
            List<Integer> result = new ArrayList<>();
            if(b!=null){
            result = listoflist.get(temp-1);
            result.add(b.val);
            }
            
            
            
        }
        int n = listoflist.size();
        for(int i = 0; i<n ; i++){
                List<Integer> element = listoflist.get(i);
                List<Integer> l1 = new ArrayList(element);
                Collections.reverse(element);
                List<Integer> l2 = new ArrayList(element);
                
                if(!(l1.equals(l2))){
                    return false;
                }
            }
        return true;
    }
}
Leave a Comment