You are given an integer. You have to print the valid paranthesis set corresponding to the number n.
Example: Number n = 2 Valid paranthesis set is ( ) ( ) ( ( ) )
Number n = 3 Valid paranthesis set is ( ) ( ) ( ) ( ( ) ( ) ) ( ( ( ) ) )
Logic:
Represent the bracket pairs as a combination of 1 and 0. Like ( ) is 1 0, ( ( ) ) is 1 1 0 0, ( ( ( ) ) )  is 1 1 1 0 0 0
When you get n as the input create a tree having the right child as 1 and left child as 0
for n = 2 structure of the tree would be
                                                           
-----------------(1)
----------------/       \
---------------/--             \
--------------(0)            (1)
--------------\----                     /
---------------\               --/
--------------(1)     (0)
---------------/-- /
--------------/           --/
------------(0)      -(0)
Printing the brackets: Traverse if u find the value as 1 put the character ( in the array else put the character ) in the array.
WHen the length of the array becomes equal to the number given as input. You are done print the array.
Pseudo Code to create the tree:
createTree(struct node * null, int n, int OneCount, int ZeroCount)
{
       if(root == Null)
       { 
            root =  makenode(1);
                OneCount++;
       }
 
   if( ZeroCount <>left = makenode(0);
               createTree(root->left,n,OneCount,ZeroCount);
       }
 
   if(OneCount <>right = makenode(1);
        createTree(root->right,n,OneCount,ZeroCount);
   }
}
PseudoCode To Read the Tree:
First Call will be made to this fucntion like PrintBrackets( root, n, array, 0);
PrintBrackets(struct node *root, int n, int * array, int index)
{
   if(root  == null)
   return;
   if(root->data == 1)
   array[index]= '(';
 
   if(root->data == 0)
   array[index] = ")';
   if(index == n-1)
   puts(array);
   return;
   if(root->left)
   PrintBrackets(root->left, n,array,index+1)
   if(root->right)
   PrintBrackets(root->right, n,array,index+1)
}
Subscribe to:
Post Comments (Atom)
 

No comments:
Post a Comment