您的位置:首页 > 产品设计 > UI/UE

Binary Tree Longest Consecutive Sequence

2016-12-27 09:18 302 查看
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
,not
3-2-1
,
so return 
2
.

这道题如果想简单一点做的话,就设置一个全局变量,在每一层计算的时候更新这个值。

需要注意的是,如果在当前节点跟它的左右孩子都没有办法连接起来的时候,需要返回1, 表示有一个节点,否则返回连续长度最长的那一条。

代码:

int[] longest = new int[1];
public int longestConsecutive(TreeNode root) {
if(root == null) return 0;
longest[0] = 1;
dfs(root);
return longest[0];
}
public int dfs(TreeNode root) {
if(root == null){
return 0;
}
if(root.left == null && root.right == null){
return 1;
}
int left = dfs(root.left);
int right = dfs(root.right);
if(root.left != null && root.val == (root.left.val -1)){
left +=1;
}else{
left = 0;
}
if(root.right != null && root.val == (root.right.val -1)){
right +=1;
}else{
right = 0;
}
longest[0] = Math.max(longest[0], Math.max(left, right));
int max = Math.max(right, left);
return max == 0?1:max;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: