|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text; |
| 5 | +using System.Threading.Tasks; |
| 6 | + |
| 7 | +namespace ProblemSolutions |
| 8 | +{ |
| 9 | + public class Problem687 : IProblem |
| 10 | + { |
| 11 | + public class TreeNode |
| 12 | + { |
| 13 | + public int val; |
| 14 | + public TreeNode left; |
| 15 | + public TreeNode right; |
| 16 | + public TreeNode(int x) { val = x; } |
| 17 | + } |
| 18 | + |
| 19 | + public void RunProblem() |
| 20 | + { |
| 21 | + throw new NotImplementedException(); |
| 22 | + } |
| 23 | + |
| 24 | + public int LongestUnivaluePath(TreeNode root) |
| 25 | + { |
| 26 | + /* |
| 27 | + * 树的遍历,使用的是“根、左、右”的方式; |
| 28 | + * 遍历过程中,有两个职责: |
| 29 | + * 1.左右节点和自己同值,那么加起来和最大长度比较一下; |
| 30 | + * 2.若节点的值,与父节点的值相同,那么就把左右子树最大的值,再加上自己的值,返回给父节点; |
| 31 | + * |
| 32 | + * 时间复杂度:就是把树遍历了一遍,顺便做了比较,所以是O(n); |
| 33 | + * 空间复杂度:O(1); |
| 34 | + */ |
| 35 | + |
| 36 | + if (root == null) return 0; |
| 37 | + TreeSearch(root, root.val); |
| 38 | + return maxL; |
| 39 | + } |
| 40 | + |
| 41 | + private int maxL = int.MinValue; |
| 42 | + |
| 43 | + /// <summary> |
| 44 | + /// 二叉树遍历求值 |
| 45 | + /// </summary> |
| 46 | + /// <param name="sonNode">子节点</param> |
| 47 | + /// <param name="val">父节点的值</param> |
| 48 | + /// <returns>与父节点值相同的节点个数</returns> |
| 49 | + private int TreeSearch(TreeNode sonNode, int val) |
| 50 | + { |
| 51 | + if (sonNode == null) return 0; |
| 52 | + |
| 53 | + //左右节点和自己同值,那么加起来和最大长度比较一下; |
| 54 | + var leftCount = TreeSearch(sonNode.left, sonNode.val); |
| 55 | + var rightCount = TreeSearch(sonNode.right, sonNode.val); |
| 56 | + maxL = Math.Max(leftCount + rightCount, maxL); |
| 57 | + |
| 58 | + //若节点的值,与父节点的值相同,那么就把左右子树最大的值,再加上自己的值,返回给父节点; |
| 59 | + if (sonNode.val == val) return Math.Max(leftCount, rightCount) + 1; |
| 60 | + |
| 61 | + return 0; |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments