Monday, October 5, 2020

L 298. Binary Tree Longest Consecutive Sequence ---M

 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.


A:

DFS

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int longestConsecutive(TreeNode* root) {
        int res = 0;
        helper(root,LONG_MIN,0, res);
        return res;
    }
private:
    void helper(TreeNode* root, long preValue, int preDepth, int& res ){
        if(not root)
            return;
        if(root->val == preValue+1){
            res = max(res, preDepth+1);
            helper(root->left, root->val, preDepth+1,res);
            helper(root->right,root->val, preDepth+1,res);
        }else{// not consecutive, start from 0
            res = max(res, 1);
            helper(root->left, root->val, 1, res);
            helper(root->right, root->val, 1, res);
        }
    }
};




No comments:

Post a Comment