C# solution using 2 queues


  • 0
    K
    public class Solution {
        public bool IsSymmetric(TreeNode root) {
            
            if (root == null || (root.left==null && root.right == null))
                return true;
                
            if (root.left==null || root.right == null)
                return false;      
    
            Queue q = new Queue();
            q.Enqueue(root.left);
            Queue p = new Queue();
            p.Enqueue(root.right);
            
            while (q.Count > 0 && p.Count > 0)
            {
                TreeNode n = (TreeNode)q.Dequeue();
                TreeNode m = (TreeNode)p.Dequeue();
    
                if (n.val!=m.val)
                    return false;
                    
                if ((n.left == null && m.right!= null) || (n.left != null && m.right== null) ||
                    (n.right == null && m.left!= null) || (n.right != null && m.left== null))
                    return false;
    
                if (n.left !=null)
                    q.Enqueue(n.left);
                if (n.right !=null)
                    q.Enqueue(n.right);
                if (m.right !=null)
                    p.Enqueue(m.right);
                if (m.left !=null)
                    p.Enqueue(m.left);
            }
            if (p.Count != q.Count)
                return false;
                
            return true;
        }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.