who can tell me where is the bug, thank you.


  • 0
    L

    /**

    • Definition for a binary tree node.
    • public class TreeNode {
    • int val;
      
    • TreeNode left;
      
    • TreeNode right;
      
    • TreeNode(int x) { val = x; }
      
    • }
      */

    class Solution {

    class ResultType {
    int singleDown;
    int longest;
    ResultType(int singleDown, int longest) {
        this.singleDown = singleDown;
        this.longest = longest;
    }
    

    }

    public int longestUnivaluePath(TreeNode root) {
        if(root == null) {
            return 0;
        }
        ResultType res = helper(root);
        return res.longest - 1;
    }
    
    public ResultType helper(TreeNode root) {
        if(root == null) {
            return new ResultType(0,0);
        }
        ResultType left = helper(root.left);
        ResultType right = helper(root.right);
        
        if(root.left != null && root.right != null && root.val == root.left.val && root.val == root.right.val) {
            int onesingle = Math.max(left.singleDown, right.singleDown) + 1;
            int onelongest = Math.max(left.singleDown + right.singleDown + 1, Math.max(Math.max(left.longest, right.longest), 1));
            return new ResultType(onesingle, onelongest);
        }
        else if(root.left != null && root.val == root.left.val) {
            return new ResultType(left.singleDown + 1, Math.max(left.singleDown + 1, left.longest));
        }
        else if(root.right != null && root.val == root.right.val) {
            return new ResultType(right.singleDown + 1, Math.max(right.singleDown + 1, right.longest));
        }
        else {
            return new ResultType(1, Math.max(Math.max(left.longest, right.longest), 1));
        }
    }
    

    }


Log in to reply
 

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