C# way (recursive and non-recursive)


  • 0
    G

    Recursive

    private static bool IsSymmetric(TreeNode root)
    {
    	if (root == null)
    	{
    		return true;
    	}
    	return IsSymmetric(root.left, root.right);
    }
    
    private static bool IsSymmetric(TreeNode left, TreeNode right)
    {
    	if (left == null || right == null)
    	{
    		return left == right;
    	}
    	if (left.val != right.val)
    	{
    		return false;
    	}
    	return IsSymmetric(left.left, right.right) && IsSymmetric(left.right, right.left);
    }
    

    Non-recursive

    private static bool IsSymmetric(TreeNode root)
    {
    	if (root == null)
    	{
    		return true;
    	}
    	
    	var queue = new Queue<TreeNode>();
    	queue.Enqueue(root.left);
    	queue.Enqueue(root.right);
    	while (queue.Count != 0)
    	{
    		var left = queue.Dequeue();
    		var right = queue.Dequeue();
    		
    		if (left == null && right == null)
    		{
    			continue;
    		}
    		if (left == null || right == null)
    		{
    			return false;
    		}
    		if (left.val != right.val)
    		{
    			return false;
    		}
    
    		queue.Enqueue(left.left);
    		queue.Enqueue(right.right);
    
    		queue.Enqueue(left.right);
    		queue.Enqueue(right.left);
    	}
    	return true;
    }
    

Log in to reply
 

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