Skip to content

Files

Latest commit

Mar 12, 2019
335c9d7 · Mar 12, 2019

History

History
This branch is 2352 commits behind lzl124631x/LeetCode:master.

298. Binary Tree Longest Consecutive Sequence

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
Mar 12, 2019
Mar 12, 2019

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.

Companies:
Google

Related Topics:
Tree

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(H)
class Solution {
private:
    int ans = 0;
    void preorder(TreeNode *node, TreeNode *parent, int length) {
        if (!node) return;
        length = parent && parent->val + 1 == node->val ? length + 1 : 1;
        ans = max(ans, length);
        preorder(node->left, node, length);
        preorder(node->right, node, length);
    }
public:
    int longestConsecutive(TreeNode* root) {
        preorder(root, NULL, 0);
        return ans;
    }
};