public class Solution {
int cnt;
public int countUnivalSubtrees(TreeNode root) {
cnt = 0;
isUnival(root);
return cnt;
}
private boolean isUnival(TreeNode root){
if(root == null) return true;
boolean left = isUnival(root.left);
boolean right =isUnival(root.right);
if(left && right){
if(root.left != null && root.left.val != root.val){
return false;
}
if(root.right != null && root.right.val != root.val){
return false;
}
cnt++;
return true;
}
return false;
}
}
public class Solution {
public class Tuple{
boolean isBST;
int bstSize;
int min;
int max;
public Tuple(){
max = Integer.MIN_VALUE;
min = Integer.MAX_VALUE;
isBST = true;
bstSize = 0;
}
}
public int largestBSTSubtree(TreeNode root) {
if(root == null) return 0;
Tuple tuple = helper(root);
return tuple.bstSize;
}
private Tuple helper(TreeNode root){
if(root == null) return new Tuple();
Tuple tuple = new Tuple();
Tuple left = helper(root.left);
Tuple right = helper(root.right);
//postOrder
if(!left.isBST || !right.isBST || left.max > root.val || right.min < root.val){
tuple.isBST = false;
tuple.bstSize = Math.max(left.bstSize, right.bstSize);
}else{
tuple.bstSize = 1 + left.bstSize + right.bstSize;
tuple.min = root.left != null ? left.min : root.val;
tuple.max = root.right != null ? right.max : root.val;
}
return tuple;
}
}
public class Solution {
public class Tuple{
int curLen;
int maxLen;
//TreeNode root;
int val;
public Tuple(TreeNode root){
//this.root = root;
this.val = root.val;
curLen = 1;
maxLen = 1;
}
public int maxLength(){
return Math.max(curLen, maxLen);
}
}
public int longestConsecutive(TreeNode root) {
if(root == null) return 0;
Tuple tuple = helper(root);
return tuple.maxLen;
}
private Tuple helper(TreeNode root){
if(root == null) return null;
Tuple left = helper(root.left);
Tuple right = helper(root.right);
Tuple tuple = new Tuple(root);
int leftLen = 0, rightLen = 0;
if(left != null && left.val == root.val+1){
leftLen = left.curLen;
}
if(right != null && right.val == root.val+1){
rightLen = right.curLen;
}
tuple.curLen = Math.max(leftLen, rightLen) + 1;
int subMax = 0;
if(left != null) subMax = Math.max(subMax, left.maxLen);
if(right != null) subMax = Math.max(subMax, right.maxLen);
tuple.maxLen = Math.max(tuple.curLen, subMax);
return tuple;
}
}