298-Binary-Tree-Longest-Consecutive-Sequence
Last updated
Last updated
---
``` java "down-to-up"
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int result;
private class Info{
private int base;
private int cur;
Info(int base,int cur){
this.base=base;
this.cur=cur;
}
}
public int longestConsecutive(TreeNode root) {
if(root==null){
return 0;
}
result=Integer.MIN_VALUE;
recur(root);
return result;
}
private Info recur(TreeNode root){
if(root.left==null && root.right==null){
result=Math.max(result,1);
return new Info(root.val,1);
}
Info left=null;
Info right=null;
if(root.left!=null){
left=recur(root.left);
}
if(root.right!=null){
right=recur(root.right);
}
//需要考虑的情况非常多,麻烦
if(root.left!=null && root.right!=null){
if(root.val!=left.base-1 && root.val!=right.base-1){
result=Math.max(result,1);
return new Info(root.val,1);
}
if(root.val==left.base-1&& root.val==right.base-1){
result=Math.max(result,Math.max(left.cur+1,right.cur+1));
return new Info(root.val,Math.max(left.cur+1,right.cur+1));
}else if(root.val == left.base -1){
result=Math.max(result,left.cur+1);
return new Info(root.val,left.cur+1);
}else{
result=Math.max(result,right.cur+1);
return new Info(root.val,right.cur+1);
}
}
else if(root.left!=null){
if(root.val!=left.base-1){
result=Math.max(result,1);
return new Info(root.val,1);
}
result=Math.max(result,left.cur+1);
return new Info(root.val,left.cur+1);
}else{
if(root.val!=right.base-1){
result=Math.max(result,1);
return new Info(root.val,1);
}
result=Math.max(result,right.cur+1);
return new Info(root.val,right.cur+1);
}
}
}