Skip to content

Instantly share code, notes, and snippets.

@Desolve
Created May 10, 2020 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Desolve/08af5452682a0112c7484b118310a12e to your computer and use it in GitHub Desktop.
Save Desolve/08af5452682a0112c7484b118310a12e to your computer and use it in GitHub Desktop.
0687 Longest Univalue Path
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int mx = 0;
public int longestUnivaluePath(TreeNode root) {
if (root == null) return 0;
count(root, root.val);
return mx;
}
public int count(TreeNode root, int val) {
if (root == null) return 0;
int l = count(root.left, root.val);
int r = count(root.right, root.val);
mx = Math.max(mx, l + r);
if (val == root.val) return Math.max(l, r) + 1;
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment