题目:
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 5
Longest consecutive sequence path is 3-4-5
, so return 3
.
2 3 / 2 / 1
Longest consecutive sequence path is 2-3
,not3-2-1
, so return 2
.
链接: http://leetcode.com/problems/binary-tree-longest-consecutive-sequence/
5/8/2017
算法班
参考别人的答案
O(n), O(n)
1 public class Solution { 2 int max = Integer.MIN_VALUE; 3 public int longestConsecutive(TreeNode root) { 4 if (root == null) return 0; 5 int curMax = 1; 6 getLongestConsecutive(root, curMax, root.val); 7 return max; 8 } 9 10 private void getLongestConsecutive(TreeNode root, int curMax, int parentVal) { 11 if (root == null) return; 12 if (parentVal + 1 == root.val) { 13 curMax++; 14 } else { 15 curMax = 1; 16 } 17 if (curMax > max) { 18 max = curMax; 19 } 20 getLongestConsecutive(root.left, curMax, root.val); 21 getLongestConsecutive(root.right, curMax, root.val); 22 } 23 }
官方讲解
top-down: pre-order
bottom-up: post-order
https://leetcode.com/articles/binary-tree-longest-consecutive-sequence/
更多讨论:
https://discuss.leetcode.com/category/376/binary-tree-longest-consecutive-sequence