C# code time out?


  • 0
    R

    I was just comparing the nodes layer by layer, where did the time go?

        public static bool IsSymmetric(TreeNode root)
        {
            bool isSymmetric = true;
            if (root != null)
            {
                TreeNode[] current = new TreeNode[2];
                TreeNode[] next = new TreeNode[4];
                current[0] = root.left;
                current[1] = root.right;
                int i, j, half;
                while (current.Length > 0)
                {
                    half = current.Length / 2;
                    for (i = 0, j = current.Length - 1; i < half; i++, j--)
                    {
                        if ((current[i] == current[j])
                            || (current[i] != null && current[j] != null && current[i].val == current[j].val))
                        {
                            continue;
                        }
                        else
                        {
                            isSymmetric = false;
                            break;
                        }
                    }
                    if (!isSymmetric)
                    {
                        break;
                    }
    
                    bool areAllNull = true;
                    int k = 0;
                    foreach (TreeNode node in current)
                    {
                        if (node == null)
                        {
                            k = k + 2;
                        }
                        else
                        {
                            areAllNull = false;
                            next[k++] = node.left;
                            next[k++] = node.right;
                        }
                    }
                    if (areAllNull)
                    {
                        break;
                    }
    
                    current = next;
                    next = new TreeNode[current.Length * 2];
                }
            }
            return isSymmetric;
        }

Log in to reply
 

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