# 298.Binary-Tree-Longest-Consecutive-Sequence

## 298. Binary Tree Longest Consecutive Sequence

## 题目地址

<https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/>

## 题目描述

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

## 代码

### Approach #1 Top Down DFS

Time: O(N) && Space: O(N)

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
  public int longestConsecutive(TreeNode root) {
        return dfs(root, null, 0);
  }

  private int dfs(TreeNode p, TreeNode parent, int length) {
    if (p == null)        return length;
    if (parent != null && p.val == parent.val + 1) {
      length = length + 1;
    } else {
      length = 1;
    }

    return Math.max(length, 
                   Math.max(dfs(p.left, p, length),
                           dfs(p.right, p, length)));
  }
}
```

### Approach #2 Bottom Up DFS

```java
class Solution {
  private int maxLength = 0;
  public int longestConsecutive(TreeNode root) {
    dfs(root);
    return maxLength;
  }

  private int dfs(TreeNode p) {
    if (p == null)        return 0;
    int L = dfs(p.left) + 1;
    int R = dfs(p.right) + 1;
    if (p.left != null && p.val + 1 != p.left.val) {
      L = 1;
    }
    if (p.right != null && p.val + 1 != p.right.val) {
      R = 1;
    }
    int length = Math.max(L, R);
    maxLength = Math.max(maxLength, length);
    return length;
  }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wentao-shao.gitbook.io/leetcode/graph-search/298.binary-tree-longest-consecutive-sequence.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
