https://leetcode.com/problems/longest-univalue-path/
/** * Definition for a binary tree node. * public 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 Info {
int depth;
int val;
}
class Solution {
int result;
public int longestUnivaluePath(TreeNode root) {
dfs(root);
return result;
}
public Info dfs(TreeNode node) {
if (node == null) return null;
Info leftInfo = dfs(node.left);
Info rightInfo = dfs(node.right);
Info info = new Info();
info.depth = 0;
info.val = node.val;
int length = 0;
if (leftInfo != null && leftInfo.val == node.val) {
length += leftInfo.depth + 1;
info.depth = leftInfo.depth + 1;
}
if (rightInfo != null && rightInfo.val == node.val) {
length += rightInfo.depth + 1;
info.depth = Math.max(info.depth, rightInfo.depth + 1);
}
result = Math.max(result, length);
return info;
}
}
后来发现,Info.val 始终是 node.val,所以根本不用存 Info.val 字段,直接用 node.left.val, node.right.val 代替就可以。
然后,Info 类就只剩下一个字段了,一个字段还有啥用?直接用裸的 int 了。
于是,对上面的代码进行了改造。改造后:
/** * Definition for a binary tree node. * public 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 result;
public int longestUnivaluePath(TreeNode root) {
dfs(root);
return result;
}
public int dfs(TreeNode node) {
if (node == null) return -1;
int leftDepth = dfs(node.left);
int rightDepth = dfs(node.right);
int depth = 0;
int length = 0;
if (leftDepth != -1 && node.left.val == node.val) {
length += leftDepth + 1;
depth = leftDepth + 1;
}
if (rightDepth != -1 && node.right.val == node.val) {
length += rightDepth + 1;
depth = Math.max(depth, rightDepth + 1);
}
result = Math.max(result, length);
return depth;
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/sinat_42483341/article/details/121177962
内容来源于网络,如有侵权,请联系作者删除!