classSolution { public: int maxv = 0; intdfs(TreeNode* root){ if (root == nullptr) return0; int ans = 0, cur = 0; int l = dfs(root->left), r = dfs(root->right); if (root->left != nullptr && root->left->val == root->val) { ans = l + 1; cur += l + 1; } if (root->right != nullptr && root->right->val == root->val) { ans = max(ans, r + 1); cur += r + 1; } maxv = max(maxv, cur); return ans; } intlongestUnivaluePath(TreeNode* root){ dfs(root); return maxv; } };
Python 代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution: deflongestUnivaluePath(self, root: Optional[TreeNode]) -> int: maxv = 0 defdfs(root): nonlocal maxv ifnot root: return0 ans, cur = 0, 0 l, r = dfs(root.left), dfs(root.right) if root.left and root.left.val == root.val: ans = l + 1 cur += l + 1 if root.right and root.right.val == root.val: ans = max(ans, r + 1) cur += r + 1 maxv = max(maxv, cur) return ans dfs(root) return maxv
TypeScript 代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
let max = 0; functionlongestUnivaluePath(root: TreeNode | null): number { max = 0 dfs(root) return max }; functiondfs(root: TreeNode | null): number { if (root == null) return0 let ans = 0, cur = 0, l = dfs(root.left), r = dfs(root.right) if (root.left != null && root.left.val == root.val) { ans = l + 1; cur += l + 1 } if (root.right != null && root.right.val == root.val) { ans = Math.max(ans, r + 1); cur += r + 1 } max = Math.max(max, cur) return ans }