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

LeetCode 298. Binary Tree Longest Consecutive Sequence(二叉树最长连续序列)

2016-04-17 00:08 447 查看
原题网址:https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/

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
.

方法:递归遍历,递归函数传入父节点的值,以帮助子节点判断是否连续。

/**
* 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;
private void find(TreeNode root, int parent, int count) {
if (root.val == parent+1) count ++; else count = 1;
max = Math.max(max, count);
if (root.left != null) find(root.left, root.val, count);
if (root.right != null) find(root.right, root.val, count);
}
public int longestConsecutive(TreeNode root) {
if (root == null) return 0;
max = 1;
if (root.left != null) find(root.left, root.val, 1);
if (root.right != null) find(root.right, root.val, 1);
return max;
}
}


优化:

/**
* 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 = 1;
private void find(TreeNode root, int prev, int len) {
if (prev+1 == root.val) len ++; else len = 1;
max = Math.max(max, len);
if (root.left != null) find(root.left, root.val, len);
if (root.right != null) find(root.right, root.val, len);
}
public int longestConsecutive(TreeNode root) {
if (root == null) return 0;
find(root, 0, 0);
return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: