5 lines Java Solution, Easy to Understand


  • 0
    public int longestUnivaluePath(TreeNode root) {
        if (root == null) return 0;
        int sub = Math.max(longestUnivaluePath(root.left), longestUnivaluePath(root.right));
        return Math.max(sub, helper(root.left, root.val) + helper(root.right, root.val));
    }
        
    private int helper(TreeNode node, int val) {
        if (node == null || node.val != val) return 0;
        return 1 + Math.max(helper(node.left, val), helper(node.right, val));
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.