1ms JAVA AC solution


  • 3
    W
    public class Solution {
    public int rob(TreeNode root) {
       int[] max = robHelper(root);
       return Math.max(max[0], max[1]);
    }
    
    private int[] robHelper(TreeNode node){
        int[] max = new int[2];
        if (node == null)
            return max;
        int[] left = robHelper(node.left);
        int[] right = robHelper(node.right);
        max[0] = node.val + left[1] + right[1];
        max[1] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
        return max;
    }
    

    }


  • 0
    H

    It is good to know such a performance gain can be achieved by just using the right data structure.


  • 0
    B

    It's very good.I use a class to store the searching state.As a result , my program is running 2ms.I think it the better one.


Log in to reply
 

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