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);
}
}
注意:不要對(duì)左右分支做Math.max, 這樣棧不能及時(shí)彈出,導(dǎo)致stack overflow
最好的方式是充坑,定義一個(gè)全局變量减江,在內(nèi)部update
錯(cuò)誤示范:
/**
* 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));
}
}