Sunday, November 8, 2015

 Find sum of all numbers that are formed from root to leaf path (code) expected time complexity O(n)
void DFSSearch(Node root, ref List<List<Int>> listOfRootToLeafPaths, ref List<int> curList)
{
 if (root != null)
  {
      if (curList == null) curList = new List<int>();
      curList.Add(root.value);
      If (root.left == null && root.right==null){
      listOfRootToLeafPaths.Add(curList);
      }
      DFSSearch(root.left, ref listOfRootToLeafPaths, ref curList);
      DFSSearch(root.right, ref listOfRootToLeafPaths, ref curList);
      curList.RemoveAt(curList.Length - 1); 
}
}


Combinations of  a string 
Void Combine (List<int> a, List<int> b, int start, int level, ref int Sum) 
{ 
   For (int I  = start ; I < a.Lengthi++) 
   {  
       b[level] = a[i]; 
       Sum +=  b.ToNumber(); // digits multiplied by place order of tens
       If (I < a.Length) 
            Combine(a,b, start+1,level+1) 
       B.RemoveAt(B.Length - 1);
   } 
} 

Each combination can also have different permutations that can be added to Sum
Void Permute (List<int> a, List<int> b, bool[] used, ref Sum) 
{ 
  If ( b.Length == a.Length { Sum +=  b.ToNumber(); return;} 
  For (int I = 0; I < a.Length ; i++) 
  { 
    If (used[i]) continue; 
     used[i] = true; 
     B += A[i]; 
     Permute(a, b, used, ref Sum); 
     B.RemoveAt(B.Length - 1);
     used[i] = false; 
  } 
} 


No comments:

Post a Comment