java 298.二叉树最长的连续序列(第1个).java
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 298.二叉树最长的连续序列(第1个).java相关的知识,希望对你有一定的参考价值。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int maxLen = 0;
public int longestConsecutive(TreeNode root) {
int cur = opt(root);
return Math.max(maxLen, cur); // [1]
}
private int opt(TreeNode root) {
if(root == null) return 0;
if(root.left == null && root.right == null) return 1;
int left = opt(root.left);
int right = opt(root.right);
int res = 1;
if(left > 0 && right > 0 && root.left.val - 1 == root.val && root.right.val - 1 == root.val) {
res += Math.max(left, right);
} else if (left > 0 && root.left.val - 1 == root.val) {
res += left;
} else if(right > 0 && root.right.val - 1 == root.val) {
res += right;
}
maxLen = Math.max(maxLen, res);
return res;
}
}
/*
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int longestConsecutive(TreeNode root) {
if(root == null) return 0;
return longestConsecutive(root, root.val - 1, 0, 0);
}
public int longestConsecutive(TreeNode node, int prev, int sum, int maxsum){
if(node == null) return Math.max(maxsum, sum);
if(node.val == prev + 1){
sum += 1;
}else{
sum = 1;
}
maxsum = Math.max(maxsum, sum);
return Math.max(
longestConsecutive(node.left, node.val, sum, maxsum),
longestConsecutive(node.right, node.val, sum, maxsum));
}
}
以上是关于java 298.二叉树最长的连续序列(第1个).java的主要内容,如果未能解决你的问题,请参考以下文章
java 298.二叉树最长的连续序列(第1个).java
java 298.二叉树最长的连续序列(第1个).java
java 298.二叉树最长的连续序列(第1个).java
java 298.二叉树最长的连续序列(第1个).java
549. 二叉树中最长的连续序列
[LeetCode] Binary Tree Longest Consecutive Sequence 二叉树最长连续序列