687. java最长同值路径(6-24华为面试模拟题)
1.题目:
2.题解:
将这种路径看为由跟节点延伸出去的两个箭头,分别为左头和右箭头,箭头的长度为零,路径的根节点应该为路径中最高层级的节点,这样正好满足题目描述,通过递归遍历的方式找到最长的路径。
3.代码:
class Solution {
int ans; //定义最大长度变量
public int longestUnivaluePath(TreeNode root) {
ans = 0;
arrowLength(root);
return ans;
}
public int arrowLength(TreeNode node) {
if (node == null) return 0;
int left = arrowLength(node.left);
int right = arrowLength(node.right);
int arrowLeft = 0, arrowRight = 0;
if (node.left != null && node.left.val == node.val) {
arrowLeft += left + 1;
}
if (node.right != null && node.right.val == node.val) {
arrowRight += right + 1;
}
ans = Math.max(ans, arrowLeft + arrowRight);
//路径的长度为左右两个箭头的长度。
return Math.max(arrowLeft, arrowRight);
//这里由根节点出发只能向一个方向走,所以要挑出更长的一边作为返回值。
}
}
/*作者:LeetCode
链接:https://leetcode-cn.com/problems/longest-univalue-path/solution/zui-chang-tong-zhi-lu-jing-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/
3.总结:
1.可以将最大值定义为一个类属性,这样可以在每个函数里引用而不用传值。
2.一定要先做空值判断,就是说如果这个分支节点是不存在的,那么就不能引用它的值,会报
java.lang.NullPointerException