Binary Tree Longest Consecutive Sequence
给一个binary tree, 问你怎么找其中最长的连续递增的path.
1 \ 3 / \ 2 4 \ 5
这个返回3.
解法很简单, 和找数组最大连续递增的子序列一样.
private int result = Integer.MIN_VALUE; public int longestConsecutive(TreeNode root) { if(root == null) return 0; dfs(root, 0, root); return result; } private void dfs(TreeNode root, int cur, TreeNode pre) { if(root == null) return; if(root.val == pre.val+1) cur++; else cur = 1; result = Math.max(result, cur); dfs(root.left, cur, root); dfs(root.right, cur, root); }
Leave A Comment