Java Tree Dynamic Programming


  • 0
    S

    /**

    • Definition for a binary tree node.

    • public class TreeNode {

    • int val;
      
    • TreeNode left;
      
    • TreeNode right;
      
    • TreeNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      public int rob(TreeNode root) {

       return maxRob(root);
      

      }

      public int maxRob(TreeNode root) {
      if(root == null)
      return 0;

      int pre = 0;
      
       if(root.left != null) {
           pre += maxRob(root.left);
           
           if(root.left.left != null)
               root.val += root.left.left.val;
           if(root.left.right != null)
               root.val += root.left.right.val;
       }
       if(root.right != null) {
           pre += maxRob(root.right);
            if(root.right.left != null)
               root.val += root.right.left.val;
           if(root.right.right != null)
               root.val += root.right.right.val;
       }
       
       root.val = Math.max(root.val , pre);
       
       return root.val;
      

      }
      }


Log in to reply
 

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