Дълбочина на N-арично дърво

Дълбочина на N-арично дърво

Като се има предвид ан n-арно дърво съдържащ положителни стойности на възел, задачата е да се намери дълбочина на дървото.
Забележка: Ан n-арно дърво е дърво, където всеки възел може да има нула или повече детски възли. За разлика от двоично дърво, което има най-много две деца на възел (ляво и дясно) n-арното дърво позволява множество клонове или деца за всеки възел.

Примери:

вход:

втори-по-големина-елемент-в-n-арно-дърво-2

Изход: 3
Обяснение: Най-дългият път от корена (възел 81) до листа е 81 -> 26 -> 95 или 81 -> 26 -> 86, което дава максимална дълбочина 3.

вход:

minimum-operation-to-make-every-leaf-node-equal-2

Изход: 2
Обяснение: Най-дългият път от корена (възел 4) до всеки лист (възли 5 или 7) е 2, тъй като изисква само две нива на преминаване.

Подход:

Идеята е да се изчисли дълбочина на N-арно дърво рекурсивно инициализирайте максимална дълбочина като 0, след това рекурсивно изчислете дълбочина за всяко дете и следете най-висока дълбочина срещани. Накрая добавете 1 до максималната дълбочина (за текущия възел) и върнете резултат . Този подход гарантира, че намираме най-дългата пътека от корена до всеки листов възел.

N-Ary дърво може да бъде обходено точно като нормално дърво. Просто трябва да разгледаме всички деца на даден възел и рекурсивно да извикаме тази функция на всеки възел. 

C++
   // C++ Code to find the depth of an N-ary tree   #include          using     namespace     std  ;   class     Node     {   public  :      int     data  ;      vector   <  Node  *>     children  ;      Node  (  int     val  )     {      data     =     val  ;      }   };   // Recursive function to calculate maximum depth   int     maxDepth  (  Node  *     root  )     {          // If the node is null depth is 0      if     (  !  root  )     {      return     0  ;      }      int     depth     =     0  ;      // Recur for all children and find the maximum depth      for     (  auto     child     :     root  ->  children  )     {      depth     =     max  (  depth       maxDepth  (  child  ));      }      // Add 1 to include the current node      // in the depth count      return     depth     +     1  ;   }   int     main  ()     {      // Representation of given N-ary tree      // 1      // / |     // 2 3 4      // /     // 5 6      Node  *     root     =     new     Node  (  1  );      root  ->  children  .  push_back  (  new     Node  (  2  ));      root  ->  children  .  push_back  (  new     Node  (  3  ));      root  ->  children  .  push_back  (  new     Node  (  4  ));      root  ->  children  [  0  ]  ->  children  .  push_back  (  new     Node  (  5  ));      root  ->  children  [  2  ]  ->  children  .  push_back  (  new     Node  (  6  ));      cout      < <     maxDepth  (  root  );      return     0  ;   }   
Java
   // Java Code to find the depth of an N-ary tree   import     java.util.*  ;   class   Node     {      int     data  ;      List   <  Node  >     children  ;      Node  (  int     val  )     {      data     =     val  ;      children     =     new     ArrayList   <>  ();      }   }   // Recursive function to calculate   // maximum depth   class   GfG     {          static     int     maxDepth  (  Node     root  )     {      // If the node is null depth is 0      if     (  root     ==     null  )     {      return     0  ;      }      int     depth     =     0  ;      // Recur for all children and find      // the maximum depth      for     (  Node     child     :     root  .  children  )     {      depth     =     Math  .  max  (  depth       maxDepth  (  child  ));      }      // Add 1 to include the current node       // in the depth count      return     depth     +     1  ;      }      public     static     void     main  (  String  []     args  )     {      // Representation of given N-ary tree      // 1      // / |       // 2 3 4      // /       // 5 6      Node     root     =     new     Node  (  1  );      root  .  children  .  add  (  new     Node  (  2  ));      root  .  children  .  add  (  new     Node  (  3  ));      root  .  children  .  add  (  new     Node  (  4  ));      root  .  children  .  get  (  0  ).  children  .  add  (  new     Node  (  5  ));      root  .  children  .  get  (  2  ).  children  .  add  (  new     Node  (  6  ));      System  .  out  .  println  (  maxDepth  (  root  ));      }   }   
Python
   # Python Code to find the depth    # of an N-ary tree   class   Node  :   def   __init__  (  self     val  ):   self  .  data   =   val   self  .  children   =   []   # Recursive function to calculate   # maximum depth   def   max_depth  (  root  ):   # If the node is None depth is 0   if   not   root  :   return   0   depth   =   0   # Recur for all children and    # find the maximum depth   for   child   in   root  .  children  :   depth   =   max  (  depth     max_depth  (  child  ))   # Add 1 to include the current   # node in the depth count   return   depth   +   1   if   __name__   ==   '__main__'  :   # Representation of given N-ary tree   # 1   # / |    # 2 3 4   # /    # 5 6   root   =   Node  (  1  )   root  .  children  .  append  (  Node  (  2  ))   root  .  children  .  append  (  Node  (  3  ))   root  .  children  .  append  (  Node  (  4  ))   root  .  children  [  0  ]  .  children  .  append  (  Node  (  5  ))   root  .  children  [  2  ]  .  children  .  append  (  Node  (  6  ))   print  (  max_depth  (  root  ))   
C#
   // C# Code to find the depth of an N-ary tree   using     System  ;   using     System.Collections.Generic  ;   class     Node     {      public     int     data  ;      public     List   <  Node  >     children  ;      public     Node  (  int     val  )     {      data     =     val  ;      children     =     new     List   <  Node  >  ();      }   }   // Recursive function to calculate   // maximum depth   class     GfG     {          static     int     MaxDepth  (  Node     root  )     {      // If the node is null depth is 0      if     (  root     ==     null  )     {      return     0  ;      }      int     depth     =     0  ;      // Recur for all children and find the maximum depth      foreach     (  Node     child     in     root  .  children  )     {      depth     =     Math  .  Max  (  depth       MaxDepth  (  child  ));      }      // Add 1 to include the current      // node in the depth count      return     depth     +     1  ;      }      static     void     Main  (  string  []     args  )     {      // Representation of given N-ary tree      // 1      // / |       // 2 3 4      // /       // 5 6      Node     root     =     new     Node  (  1  );      root  .  children  .  Add  (  new     Node  (  2  ));      root  .  children  .  Add  (  new     Node  (  3  ));      root  .  children  .  Add  (  new     Node  (  4  ));      root  .  children  [  0  ].  children  .  Add  (  new     Node  (  5  ));      root  .  children  [  2  ].  children  .  Add  (  new     Node  (  6  ));      Console  .  WriteLine  (  MaxDepth  (  root  ));      }   }   
JavaScript
   // JavaScript Code to find the depth    // of an N-ary tree   class     Node     {      constructor  (  val  )     {      this  .  data     =     val  ;      this  .  children     =     [];      }   }   // Recursive function to calculate    // maximum depth   function     maxDepth  (  root  )     {      // If the node is null depth is 0      if     (  !  root  )     {      return     0  ;      }      let     depth     =     0  ;      // Recur for all children and find      // the maximum depth      for     (  let     child     of     root  .  children  )     {      depth     =     Math  .  max  (  depth       maxDepth  (  child  ));      }      // Add 1 to include the current node       // in the depth count      return     depth     +     1  ;   }   // Representation of given N-ary tree   // 1   // / |    // 2 3 4   // /    // 5 6   const     root     =     new     Node  (  1  );   root  .  children  .  push  (  new     Node  (  2  ));   root  .  children  .  push  (  new     Node  (  3  ));   root  .  children  .  push  (  new     Node  (  4  ));   root  .  children  [  0  ].  children  .  push  (  new     Node  (  5  ));   root  .  children  [  2  ].  children  .  push  (  new     Node  (  6  ));   console  .  log  (  maxDepth  (  root  ));   

Изход
3 

Времева сложност: O(n), тъй като всеки възел се посещава веднъж, където n е общият брой възли в N-арното дърво.
Помощно пространство: O(h), където h е височината на дървото поради рекурсивно използване на стека за извикване.

Създаване на тест