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

For example,

1 \ 3 / \ 2 4 \ 5Longest consecutive sequence path is

`3-4-5`

, so return `3`

.2 \ 3 / 2 / 1Longest consecutive sequence path is

`2-3`

,not`3-2-1`

, so return `2`

.**Solution using global variables:**

Maintain two variables, one is the local length of the consecutive path, the other is the global variable of the longest local length.

We do a DFS, i.e, pre-order traversal of a binary tree. For each node of which value equals to the target value (parent value plus one), increase the local length. Otherwise, set the local length to 1. Meanwhile, update the global length.

**Code (Java):**

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { private int maxLen = 0; public int longestConsecutive(TreeNode root) { if (root == null) { return 0; } longestConsecutiveHelper(root, 1, root.val + 1); return maxLen; } private void longestConsecutiveHelper(TreeNode root, int length, int target) { if (root == null) { return; } int curLen = 0; if (root.val == target) { curLen = length + 1; } else { curLen = 1; } maxLen = Math.max(maxLen, curLen); longestConsecutiveHelper(root.left, curLen, root.val + 1); longestConsecutiveHelper(root.right, curLen, root.val + 1); } }

**Solution without using global variables:**

We can use the return value to pass the global maximal length. Then everything else is the same as the previous solution.

**Code (Java):**

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int longestConsecutive(TreeNode root) { if (root == null) { return 0; } return longestConsecutiveHelper(root, 0, root.val + 1); } private int longestConsecutiveHelper(TreeNode root, int curLen, int target) { if (root == null) { return curLen; } if (root.val == target) { curLen += 1; } else { curLen = 1; } int left = longestConsecutiveHelper(root.left, curLen, root.val + 1); int right = longestConsecutiveHelper(root.right, curLen, root.val + 1); return Math.max(curLen, Math.max(left, right)); } }

## No comments:

## Post a Comment