leetcode 687. Longest Univalue Path | 687. 最长同值路径(树形dp)

x33g5p2x  于2021-11-12 转载在 其他  
字(1.7k)|赞(0)|评价(0)|浏览(269)

题目

https://leetcode.com/problems/longest-univalue-path/

题解:树形 dp 套路

实现1:带有 Info 类的树形 dp
  1. /** * 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; * } * } */
  2. class Info {
  3. int depth;
  4. int val;
  5. }
  6. class Solution {
  7. int result;
  8. public int longestUnivaluePath(TreeNode root) {
  9. dfs(root);
  10. return result;
  11. }
  12. public Info dfs(TreeNode node) {
  13. if (node == null) return null;
  14. Info leftInfo = dfs(node.left);
  15. Info rightInfo = dfs(node.right);
  16. Info info = new Info();
  17. info.depth = 0;
  18. info.val = node.val;
  19. int length = 0;
  20. if (leftInfo != null && leftInfo.val == node.val) {
  21. length += leftInfo.depth + 1;
  22. info.depth = leftInfo.depth + 1;
  23. }
  24. if (rightInfo != null && rightInfo.val == node.val) {
  25. length += rightInfo.depth + 1;
  26. info.depth = Math.max(info.depth, rightInfo.depth + 1);
  27. }
  28. result = Math.max(result, length);
  29. return info;
  30. }
  31. }
实现2:不带 Info 类的树形 dp

后来发现,Info.val 始终是 node.val,所以根本不用存 Info.val 字段,直接用 node.left.val, node.right.val 代替就可以。

然后,Info 类就只剩下一个字段了,一个字段还有啥用?直接用裸的 int 了。

于是,对上面的代码进行了改造。改造后:

  1. /** * 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; * } * } */
  2. class Solution {
  3. int result;
  4. public int longestUnivaluePath(TreeNode root) {
  5. dfs(root);
  6. return result;
  7. }
  8. public int dfs(TreeNode node) {
  9. if (node == null) return -1;
  10. int leftDepth = dfs(node.left);
  11. int rightDepth = dfs(node.right);
  12. int depth = 0;
  13. int length = 0;
  14. if (leftDepth != -1 && node.left.val == node.val) {
  15. length += leftDepth + 1;
  16. depth = leftDepth + 1;
  17. }
  18. if (rightDepth != -1 && node.right.val == node.val) {
  19. length += rightDepth + 1;
  20. depth = Math.max(depth, rightDepth + 1);
  21. }
  22. result = Math.max(result, length);
  23. return depth;
  24. }
  25. }

相关文章