# 树形DP

#### 从五道题来看树形DP

##### 1.求树的最大值和最小值

``````public class Main {
class Node {
int value;
Node left;
Node right;
Node(int value) {
this.value = value;
}
}
class Data {
int max,min;
Data(int max,int min) {
this.max = max;
this.min = min;
}
}
return new Data(Integer.MIN_VALUE,Integer.MAX_VALUE);
}
}
``````
##### 2.求最大搜索二叉树的大小

``````public class Main {
class Data {
int max,min,size;
Data(int size,Node head,int min,int max) {
this.size = size;
this.max = max;
this.min = min;
}
}
return new Data(0,null,Integer.MAX_VALUE,Integer.MIN_VALUE);

int leftSize = leftData.size;
int rightSize = rightData.size;
int leftMax = leftData.max;
int leftMin = leftData.min;
int rightMax = rightData.max;
int rightMin = rightData.min;

includeHeadSize = leftSize + rightSize + 1;

}
}
``````
##### 3.求一棵二叉树上的最远距离

``````public class Main {
class Data {
int maxDistance,h;
Data(int maxDistance,int h) {
this.maxDistance = maxDistance;
this.h = h;
}
}
return new Data(0,0);
//三种可能性
int leftDistance = leftData.maxDistance;
int rightDistance = rightData.maxDistance;
int includeHeadDistace = leftData.h + 1 + rightData.h;

int maxH = Math.max(leftData.h,rightData.h) + 1;
return new Data(maxSize,maxH);
}
}
``````
##### 4.LeetCode337.打家劫舍 III

``````/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
class Solution {
class Data {
int robber_prices,no_robber_prices;
Data(int robber_prices,int no_robber_prices) {
this.robber_prices = robber_prices;
this.no_robber_prices = no_robber_prices;
}
}
return new Data(0,0);
int no_robber_prices = 0;
//首先遍历左孩子
robber_prices += leftData.no_robber_prices;
no_robber_prices += Math.max(leftData.no_robber_prices,leftData.robber_prices);
//然后遍历右孩子
robber_prices += rightData.no_robber_prices;
no_robber_prices += Math.max(rightData.no_robber_prices,rightData.robber_prices);

return new Data(robber_prices,no_robber_prices);
}
public int rob(TreeNode root) {
Data res = process(root);
return Math.max(res.robber_prices,res.no_robber_prices);
}
}
``````