# 549. Binary Tree Longest Consecutive Sequence II

**<font color=red>难度: Medium</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/

> 内容描述

```
Given a binary tree, you need to find the length of Longest Consecutive Path in Binary Tree.

Especially, this path can be either increasing or decreasing. For example, [1,2,3,4] and [4,3,2,1] are both considered valid, but the path [1,2,4,3] is not valid. On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order.

Example 1:
Input:
        1
       / \
      2   3
Output: 2
Explanation: The longest consecutive path is [1, 2] or [2, 1].
Example 2:
Input:
        2
       / \
      1   3
Output: 3
Explanation: The longest consecutive path is [1, 2, 3] or [3, 2, 1].
Note: All the values of tree nodes are in the range of [-1e7, 1e7].
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(N)******

对于每一个点，我们只要算出以它为起点的最长升序序列icr和最长降序序列dcr，那么```dcr + icr - 1```就是经过这个点的最长有序序列

然后我们怎么求以它为起点的最长升序序列icr和最长降序序列dcr呢？

开始我们将icr和dcr都设为1，因为这个点本身肯定在序列里面，然后我们要从这个点的left和right开始着手

- 我们先算出以root.left为起点的最长升序序列icr_left和最长降序序列dcr_left，然后看看root到root.left是升序还是降序
  - 如果root到root.left是升序，那么以root为起点的最长升序序列icr就是icr_left+1
  - 如果root到root.left是降序，那么以root为起点的最长降序序列dcr就是dcr_left+1
- 我们再算出以root.right为起点的最长升序序列icr_right和最长降序序列dcr_right，然后看看root到root.right是升序还是降序
  - 如果root到root.left是升序，那么以root为起点的最长升序序列icr就是max(icr_left+1, icr_right+1)
  - 如果root到root.left是降序，那么以root为起点的最长降序序列dcr就是max(dcr_left+1, dcr_right+1)
  
最后我们求出了以root为起点的最长升序序列icr和最长降序序列dcr，那么返回```dcr + icr - 1```就是经过这个点的最长有序序列
  

beats 98.68%

```python
class Solution:
    def longestConsecutive(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        def longestPath(root):
            if not root:
                return [0, 0] # [increase, decrease]
            icr, dcr = 1, 1
            if root.left:
                L = longestPath(root.left)
                if root.val == root.left.val - 1:
                    icr = L[0] + 1
                if root.val == root.left.val + 1:
                    dcr = L[1] + 1
            if root.right:
                R = longestPath(root.right)
                if root.val == root.right.val - 1:
                    icr = max(icr, R[0] + 1)
                if root.val == root.right.val + 1:
                    dcr = max(dcr, R[1] + 1)
            self.max_len = max(self.max_len, icr+dcr-1)
            return [icr, dcr]
        
        self.max_len = 0
        longestPath(root)
        return self.max_len
```






























