Created
May 10, 2020 15:14
-
-
Save Desolve/08af5452682a0112c7484b118310a12e to your computer and use it in GitHub Desktop.
0687 Longest Univalue Path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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