---
# System prepended metadata

title: 0298. Binary Tree Longest Consecutive Sequence
tags: [Leetcode, FaceBook, DFS, Medium]

---

# 0298. Binary Tree Longest Consecutive Sequence
###### tags: `Leetcode` `Medium` `FaceBook` `DFS`
Link: https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/
## 思路
注意leftLen有可能不等于回传的结果，但是函数一定要调用
## Code
```java=
class Solution {
    int maxLen = 0;
    public int longestConsecutive(TreeNode root) {
        length(root);
        return maxLen;
    }
    public int length(TreeNode root){
        int leftLen = 1, rightLen = 1;
        if(root.left!=null){
            leftLen = length(root.left)+1;
            if(root.left.val-1 != root.val){
                leftLen = 1;
            }
        }
        if(root.right!=null){
            rightLen = length(root.right)+1;
            if(root.right.val-1 != root.val){
                rightLen = 1;
            }   
        }
        
        maxLen = Math.max(maxLen, Math.max(leftLen, rightLen));
        return Math.max(leftLen, rightLen);
    }
}
```