298. Binary Tree Longest Consecutive Sequence

298. Binary Tree Longest Consecutive Sequence

  • 方法1: dfs(top-down)

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

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).

Example 1:

Input:

   1
    \
     3
    / \
   2   4
        \
         5

Output: 3

Explanation: Longest consecutive sequence path is 3-4-5, so return 3.

Example 2:

Input:

   2
    \
     3
    / 
   2    
  / 
 1

Output: 2 

Explanation: Longest consecutive sequence path is 2-3, not 3-2-1, so return 2.

方法1: dfs(top-down)

官方题解: https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/solution/

思路:

class Solution {
public:
    int longestConsecutive(TreeNode* root) {
        if (!root) return 0;
        int maxLength = 1;
        longestHelper(root, 1, maxLength, root -> val);
        return maxLength;
    }
    
    void longestHelper(TreeNode* root, int depth, int & maxLength, int prev){
        if (!root) return;
        
        if (prev + 1 == root -> val) depth += 1;
        else depth = 1;
        
        maxLength = max(maxLength, depth);
        
        longestHelper(root -> left, depth, maxLength, root -> val);
        longestHelper(root -> right, depth, maxLength, root -> val);
    }
};

你可能感兴趣的:(298. Binary Tree Longest Consecutive Sequence)