LeetCode.M687.最长同值路径
题目:
题目大意:
求一个二叉树中的最大路径,这个最大路径上的节点值都是一样的。比如下图,分析下图可知,node2 所在的最大路径是由 node2 的左右孩子节点组成的(比如红色路径)。
数据范围:
如图所示
思路:
以 node2 为例,我们递归的求以该节点延伸出的左右孩子的路径长度。l, r。更新 ans = max(ans, l + r + 1)。
当node2.val == node1.val(其父节点的值)时,需要返回 max(l, r) + 1。代表了从 node1 节点的左孩子(node2)延伸出的的路径。
当node2.val != node1.val 时,需要返回 0,代表了从 node1 节点的左孩子往下延伸没有路径。
这样的话 node1节点的左孩子路径 l 就求出了,其右孩子路径 r 同理,这样以 node1 向其左右孩子延伸出的路径 l + r + 1,就求出了,再更新一下 ans = max(ans, l + r + 1) 即可。
代码:
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
int ans = -1;
public int dfs(TreeNode root, int pval){
if (root == null)
return 0;
int l = dfs(root.left, root.val), r = dfs(root.right, root.val);
ans = Math.max(ans, l + r + 1);
if (pval == root.val){
return Math.max(l, r) + 1;
}else {
return 0;
}
}
public int longestUnivaluePath(TreeNode root) {
if (root == null)
return 0;
dfs(root, (int)-1e9);
return ans - 1;
}
}
public class Main {
public static void main(String[] args) {
Solution solution = new Solution();
TreeNode node1 = new TreeNode(1);
System.out.println(solution.longestUnivaluePath(node1));
}
}
时空复杂度分析等:
-
时间复杂度 : O(n)
-
空间复杂度 : O(n)