JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

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.

Code

549. Binary Tree Longest Consecutive Sequence II

class Solution {
    int res = 1;
    
    public int longestConsecutive(TreeNode root) {
        if (root == null) return 0;
        
        helper(root, root.val, 0);
        return res;
    }
    
    private void helper(TreeNode root, int curr, int count){
        if (root == null) return;
        if (root.val == curr){
            count++;
            res = Math.max(res, count);
            helper(root.left, curr + 1, count);
            helper(root.right, curr + 1, count);
        } else {
            helper(root.left, root.val + 1, 1);
            helper(root.right, root.val + 1, 1);
        }
    }
}
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    res = 1

    def count(self, node: TreeNode, num: int, should_val: int) -> None:
        if not node:
            return
        if should_val == node.val:
            self.res = max(self.res, num + 1)
            self.count(node.left, num + 1, should_val + 1)
            self.count(node.right, num + 1, should_val + 1)
        else:
            self.count(node.left, 1, node.val + 1)
            self.count(node.right, 1, node.val + 1)

    def longestConsecutive(self, root: TreeNode) -> int:
        if not root:
            return 0
        self.count(root, 0, root.val)
        return self.res