/*
* 298. Binary Tree Longest Consecutive Sequence My Submissions QuestionEditorial Solution
Total Accepted: 9973 Total Submissions: 26688 Difficulty: Medium
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.
Hide Company Tags Google
Hide Tags Tree
Hide Similar Problems (H) Longest Consecutive Sequence
*/
package tree;
public class BinaryTreeLongestConsecutiveSeq {
int max = 0;
public int longestConsecutive(TreeNode root) {
/* https://discuss.leetcode.com/topic/28234/easy-java-dfs-is-there-better-time-complexity-solution
Just very intuitive depth-first search,
send cur node value to the next level and compare it with the next level node.
*/
if (root == null) return 0;
helper(root, 0, root.val + 1);
return max;
}
public void helper(TreeNode root, int cur, int target) {
if (root == null) return;
if (root.val == target) {
cur++;
} else {
cur = 1;
}
max = Math.max(cur, max);
helper(root.left, cur, root.val + 1);
helper(root.right, cur, root.val + 1);
}
// doesn't work. 我的方法不凑效
public int dfs(TreeNode root, int count) {
if (root == null) return count;
if (root.right == null && root.left == null) {
return count;
}
if (root.left != null) {
if (root.val > root.left.val) {
dfs(root.left, count + 1);
}
}
if (root.right != null) {
if (root.val > root.right.val) {
dfs(root.right, count + 1);
}
}
return count;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
TreeNode three = new TreeNode(3);
root.right = three;
three.left = new TreeNode(2);
TreeNode four = new TreeNode(4);
three.right = four;
four.right = new TreeNode(5);
BinaryTreeLongestConsecutiveSeq blcs = new BinaryTreeLongestConsecutiveSeq();
int result = blcs.longestConsecutive(root);
System.out.println(result); // 3
}
}
298. Binary Tree Longest Consecutive Sequence
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Given a binary tree, find the length of the longest conse...
- 原题 给一个二叉树,求其中最长连续序列的长度 样例比如,下面的树,最长序列为3->4->5,返回3 解题思路 递归...
- Given a binary tree, find the length of the longest conse...
- Math.max(current count, Math.max(leftSubtree, rightSubtre...
- 不得不说,Tree的题还算挺有意思的。首先给出two pass的做法: pass one找往下的sequence,...