Bottom Up DP approach keeping data structure with and without including root value.


  • 0
    M
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Node {
    	int withRoot;
    	int withoutRoot;
    
    	Node(int withRoot, int withoutRoot) {
    		this.withRoot = withRoot;
    		this.withoutRoot = withoutRoot;
    	}
    }
    
    public class Solution {
    	public int rob(TreeNode root) {
    		Node n = robNode(root);
    		return Math.max(n.withRoot, n.withoutRoot);
    	}
    
    	private Node robNode(TreeNode root) {
    		if(root==null) {
    			return new Node(0, 0);
    		}
    		if (root.left == null && root.right == null) {
    			return new Node(root.val, 0);
    		}
    		Node l = robNode(root.left);
    		Node r = robNode(root.right);
    		int withoutRoot = Math.max(l.withRoot, l.withoutRoot)
    				+ Math.max(r.withRoot, r.withoutRoot);
    		int withRoot = root.val + l.withoutRoot + r.withoutRoot;
    		return new Node(withRoot, withoutRoot);
    	}
    
    }

Log in to reply
 

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