C# Iterative using stack Accepted


  • 0
    S
    public bool IsSymmetric(TreeNode root) 
    {
        if (root == null) 
            return true;
    
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.Push(root.left);
        stack.Push(root.right);
        
        while (stack.Count() > 0) 
        {
            TreeNode n1 = stack.Pop();
            TreeNode n2 = stack.Pop();
            
            if (n1 == null && n2 == null) 
                continue;
            
            if (n1 == null || n2 == null || n1.val != n2.val) 
                return false;
                
            stack.Push(n1.left);
            stack.Push(n2.right);
            
            stack.Push(n1.right);
            stack.Push(n2.left);
        }
        return true;
    }

Log in to reply
 

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