原题:#687_最长同值路径
- 最长同值路径存在情况:
- 经过根节点
- 在左子树内部
- 在右子树内部
- 递归:
- 返回值:最长的同值路径长度(在左子树或右子树中)
- 结束条件:当前根节点为空
- 递归操作:求出当前节点的左子树最长同值长度,右子树最长同值长度。相加后与已保存的当前最长同值长度相比然后更新。
- 递归过程中:
- 若当前节点与它的左/右子树的节点值不相同,则该左/右子树的最长同值长度为0;
- 若相同,则为左/右子树最长路径长度+1(根节点)
- 递归过程中:
int ans;
public int a (TreeNode root) {
ans = 0;
b (root);
return ans;
}
public int b (TreeNode node) {
if (node == null) return 0;
int left = b (node.left); //求出左子树最长同值路径
int right = b (node.right);
int lLength = 0, rLength = 0;
if (node.left != null && node.left.val == node.val) {
lLength = left + 1; //+1是加上根节点
}
if (node.right != null && node.right.val == node.val) {
rLength = right + 1;
}
ans = Math.max(ans, rLength + lLength); //不断更新
return Math.max(rLength,lLength); //返回最长的同值路径给根节点
}