298. Binary Tree Longest Consecutive Sequence

Given a binary tree, find the length of the longest consecutive sequence path.node

The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).this

Example 1:spa

Input:

   1
    \
     3
    / \
   2   4
        \
         5

Output: 

Explanation: Longest consecutive sequence path is , so return .33-4-53

Example 2:code

Input:

   2
    \
     3
    / 
   2    
  / 
 1

Output: 2 

Explanation: Longest consecutive sequence path is , not , so return .2-33-2-12

 

class Solution {
    private int maxLength = 0;
    public int longestConsecutive(TreeNode root) {
      helper(root);
      
      return maxLength;
        
    }
    private int helper(TreeNode root){
      if(root == null){
        return 0;
      }
      
        
    // 拿 左边和右边的 值 
      int left = helper(root.left);
      int right = helper(root.right);
        
        
    // 决定当前的值 应该什么, 当前的 值 和 左边 的 , 还有 右边的 值 都有关系
      
      if(root.left != null && root.left.val == root.val + 1){
        left = left + 1; // 若是能够加的上
      }else{
        left = 1; // 加不上
      }
      
      
      if(root.right != null && root.right.val == root.val + 1){
        right = right + 1; // same as above 
      }else{
        right = 1;
      }
      
      int length = Math.max(left, right); // 返回 单方向的 一条 path 值
        
      maxLength = Math.max(length, maxLength); // update global max 
      
      return length; // 带返回值的recursion 
    }
}

// time : o(n), space, o(height)

// this is smiliar to another problem similar to this one, in a way that 
// when you wonder , what if the result is actually starting from some nodes in the middle
// because 当你往上传值得时候, 下面的全部的状况已经计算好了, 也是按照这个recursion 的 步骤 进行的, 
// 这道题和 那个  max paths sum from any node to any node 像, 由于 最后答案中的 root 能够是 任何一个 node。 
// 因此 这个题 就是 以每一个 node 为 root 的 结果 都要探索一遍。 这两个好像都是从下往上传的值, 

// Input:

//    1
//     \
//      3
//     / \
//    2   4
//         \
//          5

// Output: 3

// Explanation: Longest consecutive sequence path is 3-4-5, so return 3.
相关文章
相关标签/搜索