Simple C# solution. Traversing both sides of tree simultaneous.


  • 0
    S
    public bool IsSymmetric(TreeNode root) {
            if(root == null)
            {
                return true;
            }
            Stack<Tuple<TreeNode, TreeNode>> S = new Stack<Tuple<TreeNode, TreeNode>>();
            Tuple<TreeNode,TreeNode> T = new Tuple<TreeNode, TreeNode>(root.left, root.right);
            S.Push(T);
            while(S.Count!=0)
            {
                var curr = S.Pop();
                if(curr.Item1 == null || curr.Item2 == null)
                {
                    if(curr.Item1 == null && curr.Item2 == null)
                    {
                        continue;
                    }
                    else
                    {
                        return false;
                    }
                }
                else if(curr.Item1.val == curr.Item2.val)
                {
                    S.Push(new Tuple<TreeNode, TreeNode>(curr.Item1.left, curr.Item2.right));
                    S.Push(new Tuple<TreeNode, TreeNode>(curr.Item1.right, curr.Item2.left));
                }
                else
                {
                    return false;
                }
            }
            return true;
        }
    
    

Log in to reply
 

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