Sequência consecutiva mais longa na árvore binária

Sequência consecutiva mais longa na árvore binária
Experimente no GfG Practice Sequência consecutiva mais longa na árvore binária #practiceLinkDiv { display: nenhum! Importante; }

Dada uma árvore binária, encontre o comprimento do caminho mais longo que compreende nós com valores consecutivos em ordem crescente. Cada nó é considerado um caminho de comprimento 1.
Exemplos:  
 

In below diagram binary tree with longest consecutive path(LCP) are shown : 

Prática recomendada Sequência consecutiva mais longa na árvore binária Experimente!

Podemos resolver o problema acima recursivamente. Em cada nó, precisamos de informações de seu nó pai, se o nó atual tiver valor um a mais que seu nó pai, então ele faz um caminho consecutivo em cada nó, compararemos o valor do nó com seu valor pai e atualizaremos o caminho consecutivo mais longo de acordo. 

Para obter o valor do nó pai, passaremos (node_value + 1) como um argumento para o método recursivo e compararemos o valor do nó com o valor deste argumento se for satisfatório, atualize o comprimento atual do caminho consecutivo, caso contrário, reinicialize o comprimento do caminho atual em 1. 

Por favor, veja o código abaixo para melhor compreensão: 

C++
   // C/C++ program to find longest consecutive   // sequence in binary tree   #include          using     namespace     std  ;   /* A binary tree node has data pointer to left    child and a pointer to right child */   struct     Node   {      int     data  ;      Node     *  left       *  right  ;   };   // A utility function to create a node   Node  *     newNode  (  int     data  )   {      Node  *     temp     =     new     Node  ;      temp  ->  data     =     data  ;      temp  ->  left     =     temp  ->  right     =     NULL  ;      return     temp  ;   }   // Utility method to return length of longest   // consecutive sequence of tree   void     longestConsecutiveUtil  (  Node  *     root       int     curLength        int     expected       int  &     res  )   {      if     (  root     ==     NULL  )      return  ;      // if root data has one more than its parent      // then increase current length      if     (  root  ->  data     ==     expected  )      curLength  ++  ;      else      curLength     =     1  ;      // update the maximum by current length      res     =     max  (  res       curLength  );      // recursively call left and right subtree with      // expected value 1 more than root data      longestConsecutiveUtil  (  root  ->  left       curLength        root  ->  data     +     1       res  );      longestConsecutiveUtil  (  root  ->  right       curLength        root  ->  data     +     1       res  );   }   // method returns length of longest consecutive   // sequence rooted at node root   int     longestConsecutive  (  Node  *     root  )   {      if     (  root     ==     NULL  )      return     0  ;      int     res     =     0  ;      // call utility method with current length 0      longestConsecutiveUtil  (  root       0       root  ->  data       res  );      return     res  ;   }   // Driver code to test above methods   int     main  ()   {      Node  *     root     =     newNode  (  6  );      root  ->  right     =     newNode  (  9  );      root  ->  right  ->  left     =     newNode  (  7  );      root  ->  right  ->  right     =     newNode  (  10  );      root  ->  right  ->  right  ->  right     =     newNode  (  11  );      printf  (  '%d  n  '       longestConsecutive  (  root  ));      return     0  ;   }   
Java
   // Java program to find longest consecutive    // sequence in binary tree   class   Node   {      int     data  ;      Node     left       right  ;      Node  (  int     item  )      {      data     =     item  ;      left     =     right     =     null  ;      }   }   class   Result      {      int     res     =     0  ;   }   class   BinaryTree   {      Node     root  ;      // method returns length of longest consecutive       // sequence rooted at node root       int     longestConsecutive  (  Node     root  )      {      if     (  root     ==     null  )      return     0  ;      Result     res     =     new     Result  ();          // call utility method with current length 0       longestConsecutiveUtil  (  root       0       root  .  data       res  );          return     res  .  res  ;      }      // Utility method to return length of longest       // consecutive sequence of tree       private     void     longestConsecutiveUtil  (  Node     root       int     curlength           int     expected       Result     res  )      {      if     (  root     ==     null  )      return  ;      // if root data has one more than its parent       // then increase current length       if     (  root  .  data     ==     expected  )      curlength  ++  ;      else      curlength     =     1  ;      // update the maximum by current length       res  .  res     =     Math  .  max  (  res  .  res       curlength  );      // recursively call left and right subtree with       // expected value 1 more than root data       longestConsecutiveUtil  (  root  .  left       curlength       root  .  data     +     1       res  );      longestConsecutiveUtil  (  root  .  right       curlength       root  .  data     +     1       res  );      }      // Driver code      public     static     void     main  (  String     args  []  )         {      BinaryTree     tree     =     new     BinaryTree  ();      tree  .  root     =     new     Node  (  6  );      tree  .  root  .  right     =     new     Node  (  9  );      tree  .  root  .  right  .  left     =     new     Node  (  7  );      tree  .  root  .  right  .  right     =     new     Node  (  10  );      tree  .  root  .  right  .  right  .  right     =     new     Node  (  11  );      System  .  out  .  println  (  tree  .  longestConsecutive  (  tree  .  root  ));      }   }   // This code is contributed by shubham96301   
Python3
   # Python3 program to find longest consecutive    # sequence in binary tree    # A utility class to create a node    class   newNode  :   def   __init__  (  self     data  ):   self  .  data   =   data   self  .  left   =   self  .  right   =   None   # Utility method to return length of    # longest consecutive sequence of tree    def   longestConsecutiveUtil  (  root     curLength     expected     res  ):   if   (  root   ==   None  ):   return   # if root data has one more than its    # parent then increase current length    if   (  root  .  data   ==   expected  ):   curLength   +=   1   else  :   curLength   =   1   # update the maximum by current length    res  [  0  ]   =   max  (  res  [  0  ]   curLength  )   # recursively call left and right subtree    # with expected value 1 more than root data    longestConsecutiveUtil  (  root  .  left     curLength     root  .  data   +   1     res  )   longestConsecutiveUtil  (  root  .  right     curLength     root  .  data   +   1     res  )   # method returns length of longest consecutive    # sequence rooted at node root    def   longestConsecutive  (  root  ):   if   (  root   ==   None  ):   return   0   res   =   [  0  ]   # call utility method with current length 0    longestConsecutiveUtil  (  root     0     root  .  data     res  )   return   res  [  0  ]   # Driver Code   if   __name__   ==   '__main__'  :   root   =   newNode  (  6  )   root  .  right   =   newNode  (  9  )   root  .  right  .  left   =   newNode  (  7  )   root  .  right  .  right   =   newNode  (  10  )   root  .  right  .  right  .  right   =   newNode  (  11  )   print  (  longestConsecutive  (  root  ))   # This code is contributed by PranchalK   
C#
   // C# program to find longest consecutive    // sequence in binary tree    using     System  ;      class     Node      {         public     int     data  ;         public     Node     left       right  ;         public     Node  (  int     item  )         {         data     =     item  ;         left     =     right     =     null  ;         }      }      class     Result      {         public     int     res     =     0  ;      }      class     GFG      {         Node     root  ;         // method returns length of longest consecutive       // sequence rooted at node root       int     longestConsecutive  (  Node     root  )         {         if     (  root     ==     null  )         return     0  ;         Result     res     =     new     Result  ();             // call utility method with current length 0       longestConsecutiveUtil  (  root       0       root  .  data       res  );             return     res  .  res  ;         }         // Utility method to return length of longest       // consecutive sequence of tree       private     void     longestConsecutiveUtil  (  Node     root       int     curlength           int     expected       Result     res  )         {         if     (  root     ==     null  )         return  ;         // if root data has one more than its parent       // then increase current length       if     (  root  .  data     ==     expected  )         curlength  ++  ;         else      curlength     =     1  ;         // update the maximum by current length       res  .  res     =     Math  .  Max  (  res  .  res       curlength  );         // recursively call left and right subtree with       // expected value 1 more than root data       longestConsecutiveUtil  (  root  .  left       curlength           root  .  data     +     1       res  );         longestConsecutiveUtil  (  root  .  right       curlength           root  .  data     +     1       res  );         }         // Driver code       public     static     void     Main  (  String     []  args  )         {         GFG     tree     =     new     GFG  ();         tree  .  root     =     new     Node  (  6  );         tree  .  root  .  right     =     new     Node  (  9  );         tree  .  root  .  right  .  left     =     new     Node  (  7  );         tree  .  root  .  right  .  right     =     new     Node  (  10  );         tree  .  root  .  right  .  right  .  right     =     new     Node  (  11  );         Console  .  WriteLine  (  tree  .  longestConsecutive  (  tree  .  root  ));         }      }      // This code is contributed by 29AjayKumar   
JavaScript
    <  script  >   // JavaScript program to find longest consecutive    // sequence in binary tree   class     Node   {      constructor  (  item  )      {      this  .  data  =  item  ;      this  .  left     =     this  .  right     =     null  ;      }   }   let     res     =     0  ;   let     root  ;   function     longestConsecutive  (  root  )   {      if     (  root     ==     null  )      return     0  ;          res  =  [  0  ];             // call utility method with current length 0       longestConsecutiveUtil  (  root       0       root  .  data       res  );          return     res  [  0  ];   }      // Utility method to return length of longest       // consecutive sequence of tree    function     longestConsecutiveUtil  (  root    curlength       expected    res  )   {      if     (  root     ==     null  )      return  ;          // if root data has one more than its parent       // then increase current length       if     (  root  .  data     ==     expected  )      curlength  ++  ;      else      curlength     =     1  ;          // update the maximum by current length       res  [  0  ]     =     Math  .  max  (  res  [  0  ]     curlength  );          // recursively call left and right subtree with       // expected value 1 more than root data       longestConsecutiveUtil  (  root  .  left       curlength           root  .  data     +     1       res  );      longestConsecutiveUtil  (  root  .  right       curlength           root  .  data     +     1       res  );   }   // Driver code   root     =     new     Node  (  6  );   root  .  right     =     new     Node  (  9  );   root  .  right  .  left     =     new     Node  (  7  );   root  .  right  .  right     =     new     Node  (  10  );   root  .  right  .  right  .  right     =     new     Node  (  11  );   document  .  write  (  longestConsecutive  (  root  ));   // This code is contributed by rag2127    <  /script>   

Saída
3 

Complexidade de tempo: O(N) onde N é o número de nós em uma determinada árvore binária.
Espaço Auxiliar: O(log(N))
Também discutido no link abaixo: 
Comprimento máximo do caminho crescente consecutivo na árvore binária

 

Criar questionário