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.
一刷
题解:利用DFS
/**
* 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 max = 0;
public int longestConsecutive(TreeNode root) {
if(root == null) return max;
findlongest(root, 0, root.val);
return max;
}
private void findlongest(TreeNode root, int curMax, int target){
if(root==null) return;
if(root.val == target) curMax++;
else curMax = 1;
max = Math.max(max, curMax);
findlongest(root.left, curMax, root.val+1);
findlongest(root.right, curMax, root.val+1);
}
}
二刷
DFS
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int max = 0;
public int longestConsecutive(TreeNode root) {
if(root == null) return max;
findLongest(root, 0, root.val);
return max;
}
private void findLongest(TreeNode root, int curMax, int target){
if(root == null) return;
if(root.val == target) curMax++;
else curMax = 1;
max = Math.max(curMax, max);
findLongest(root.left, curMax, root.val + 1);
findLongest(root.right, curMax, root.val + 1);
}
}
注意:不要对左右分支做Math.max, 这样栈不能及时弹出,导致stack overflow
最好的方式是,定义一个全局变量,在内部update
错误示范:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int longestConsecutive(TreeNode root) {
if(root == null) return 0;
return Math.max(heler(root.left, root.val+1, 1),
heler(root.right, root.val+1, 1));
}
public int heler(TreeNode node, int target, int len){
if(node == null) return len;
if(node.val != target) return Math.max(len, longestConsecutive(node));
else return Math.max(heler(node.left, node.val+1, len+1),
heler(node.right, node.val+1, len+1));
}
}